思路:
- 先定义两个变量存储两个字符串的长度
- 定义count记录子字符串出现的次数,每出现一次count++
- 定义index记录第一次出现的索引位置
- 调用indexOf方法,未出现子串的话会返回-1,所以返回值不等于-1,就是子串出现一次,就可以count++
- count++后,将index调整为出现子串的索引位置加上子串的长度,然后再进行判断,直到返回-1,return count
/**
* 获取一个字符串在另一个字符串中出现的次数
* @author xixi
* @create 2020-04-19 20:31
*/
public class Test3 {
public static void main(String[] args) {
String mainStr = "qwertyuiopqwertyuiop";
String subStr = "we";
Test3 t = new Test3();
System.out.println(t.getCount(mainStr, subStr));
}
public int getCount(String mainStr,String subStr){
int mainLength = mainStr.length();
int subLength = subStr.length();
int count = 0;
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;
}
}