string面试题
题目一:
/**
* @author terry
* 将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为”abfedcg”
*/
题解:
//方式一:
public String reveerse( String str,int start,int end){
if (str != null){
char[] arr = str.toCharArray();
for (int x = start , y = end ; x < y ; x++, y--) {
char temp = arr[x];
arr[x] =arr[y];
arr[y] = temp;
}
return new String(arr);
}
return null;
}
//方式二
public String revrse( String str , int start,int end){
if (str != null){
String revrsestr = str.substring(0,start);
for (int i = end; i >= start;i--){
revrsestr+=str.charAt(i);
}
revrsestr+=str.substring(end+1);
return revrsestr;
}
return null;
}
//方式三
public String revrse1(String str,int start,int end){
if (str != null){
StringBuilder builder = new StringBuilder(str.length()); //有容量的构造器
//
builder.append(str.substring(0,start));
//
for (int i = end ; i >= start ;i--){
builder.append(str.charAt(i));
}
//
builder.append(str.substring(end+1));
return builder.toString();
}
return null;
}
题目二:
获取一个字符串在另一个字符串中出现的次数。
比如:获取“ ab”在 “abkkcadkabkebfkabkskab” 中出现的次数
public int getCount(String mainstr,String substr){
int count = 0 ;
int mainlength = mainstr.length();
int sublength =substr.length();
int index = 0;
if (mainlength > sublength){
// while ((index=mainstr.indexOf(substr))!=-1){
//
// count++;
//
// mainstr = mainstr.substring(index + substr.length());
//
// }
while ((index = mainstr.indexOf(substr,index))!=-1){
count++;
index +=sublength;
}
return count;
}else
return 0;
}
题目三:
/*
获取两个字符串中最大相同子串。比如:
str1 = "abcwerthelloyuiodefabcdef";str2 = "cvhellobnm"
提示:将短的那个串进行长度依次递减的子串与较长的串比较。
*/
//前提:两个字符串中只有一个最大相同子串
public String getMaxSameString(String str1,String str2){
if(str1 != null && str2 != null){
String maxStr = (str1.length() >= str2.length())? str1 : str2;
String minStr = (str1.length() < str2.length())? str1 : str2;
int length = minStr.length();
for(int i = 0;i < length;i++){
for(int x = 0,y = length - i;y <= length;x++,y++){
String subStr = minStr.substring(x,y);
if(maxStr.contains(subStr)){
return subStr;
}
}
}
}
return null;
}