String的常见操作(面试题)
将字符串逆序输出
public static String inverse(String str ){
char chars[] = str.toCharArray();
for(int i=0;i<chars.length/2;i++){
char temp = chars[i];
chars[i] = chars[chars.length-i-1];
chars[chars.length-i-1] = temp ;
}
return String.valueOf(chars) ;
}
返回出现频率最高的字符
public static char findHighRateChar(String str){
int max_num_char = 0;
char highRateChar = ' ';
Map<String,Integer> map = new HashMap<String,Integer>();
char chars[] = str.toCharArray();
for(int i=0;i<chars.length;i++){
String char_i = String.valueOf(chars[i]);
if(map.containsKey(char_i)){
map.put(char_i,map.get(char_i)+1);
if(map.get(char_i) > max_num_char ){
max_num_char = map.get(char_i);
highRateChar = chars[i];
}
}else{
map.put(String.valueOf(chars[i]),1);
}
}
return highRateChar;
}
找出字符串中最长的那个对称字符串
public static String findMaxSymmetryStr(String str){
String symmetryStr;
for (int i = str.length(); i >=2; i--) {
for (int j = 0; j<i-1 ; j++) {
symmetryStr = str.substring(j, i);
char[] chars = symmetryStr.toCharArray();
int k;
for (k = 0; k < chars.length/2; k++) {
if(chars[k] != chars[chars.length-k-1]){
break;
}
}
if(k == chars.length/2){
return symmetryStr;
}
}
}
return "";
}
找字符串中共有多少个对称的字符串
public static int findSymmetryStrNum(String str){
String symmetryStr;
int count = 0;
for(int i=str.length();i>=2;i--){
for(int j=0;j<i-1;j++){
char temp[] = str.substring(j,i).toCharArray();
int k;
for(k=0;k<temp.length/2;k++){
if(temp[k] != temp[temp.length-k-1]){
break;
}
}
if(k == temp.length/2){
count++;
}
}
}
return count;
}