求字符串中的子串出现的次数
package com.ycy3;
public class Test04 {
public static void main(String[] args) {
String str1 = "xyabcdabtr";
String str2 = "ab";
Test04 test = new Test04();
int counter = test.getCounter(str1, str2);
System.out.println(counter);
}
public int getCounter(String rawString,String subString) {
int counter = 0;
int index = rawString.indexOf(subString);
while(index >= 0) {
counter ++;
rawString = rawString.substring(index + subString.length());
index = rawString.indexOf(subString);
}
return counter;
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8bb463ab241c57b43e5d00baf261f133.png)