获取一个字符串中,另一个字符串出现的次数
思想:
- indexOf到字符串中到第一次出现的索引
- 找到的索引+被找字符串长度,截取字符串
- 计数器++
4.图解
代码:
public static int getStringCount(String str, String key){
//定义计数器
int count = 0;
//定义变量,保存indexOf查找后的索引的结果
int index = 0;
//开始循环找,条件,indexOf==-1 字符串没找到
while(( index = str.indexOf(key) )!= -1){
count++;
//获取到的索引,和字符串长度求和,截取字符串
str = str.substring(index+key.length());
}
return count;
}