String练习题
题目一
任务:将字符串中间的字符(除头尾外的其他字符)反转,
如"abc123"中的bc12反转再拼接a3,变成 a21cb3
public class work {
public static void main(String[] args) {
String str = "abc123";
reverse(str,1, str.length()-1);
}
public static void reverse(String str,int startIndex,int endIndex){
// 切割字符串指定的位置
String a1 = str.substring(startIndex, endIndex);
// 转换成StringBuilder类型方便字符串反转
StringBuilder sb = new StringBuilder(a1);
// 再将反转后的StringBuilder转换成String,方便字符串拼接
sb.reverse();
// 拼接一头一尾
sb.insert(0, str.substring(0, startIndex));
str = sb.insert(sb.length(), str.charAt(endIndex)).toString();
System.out.println(str);// a21cb3
}
}
题目二
判断一个字符串在另一个字符串中出现的次数
public class Work02 {
public static void main(String[] args) {
String mainStr = "dsfadswesfsdfasfdsf";
String subStr = "sf";
System.out.println(compare(mainStr,subStr));
}
public static int compare(String mainStr,String subStr){
int mainLength = mainStr.length();
int subLength = subStr.length();
// 记录查询的次数
int count = 0;
// 记录查询到的位置
int index = 0;
if (mainStr != null || subStr != null){
if (mainLength >= subLength){
while ((index = mainStr.indexOf(subStr, index)) != -1){
count++;
// 往查询到的字符串后面查询
index += subLength;
}
return count;
}else {
return 0;
}
}else {
return 0;
}
}
}
题目三