1、题目要求
:在这个字符串中"klfjsdfwofjwokzljwo" 有多少个wo字?
方法一:最笨的方法
// 定义字符串
String str="klfjsdfwofjwokzljwo";
// 定义子串
String sub="wo";
// indexOf(String str)返回字符串第一次出现的索引
int index=str.indexOf(sub);
System.out.println(index);
// 第一次出现在索引7,则第二次从索引9(index+sub.length())开始
index=str.indexOf(sub,index+sub.length());
System.out.println(index);
// 同上
index=str.indexOf(sub,index+sub.length());
System.out.println(index);
}
方法二:while循环,每次下标值自动加子串的长度
// 定义字符串
String str="klfjsdfwofjwokzljwo";
// 定义子串
String sub="wo";
// 通过循环来计算索引出现的次数来得到结果
int count=0; // 计数器初始为0
int index=0; // 下标初始我0
// 判断首次在字符串是否能找到子串,有就使计数器+1,下标值自动+sub.length
while ((index=str.indexOf(sub,index))!=-1) {
count++;
index=index+sub.length();
}
System.out.println(count);
}