我们可以使用indexOf(String)这个函数,来返回子串出现的第一个位置,然后通过indexOf(int,String)
来查找下一个子串的位置,每次都加上子串的长度
private static int getKeyCount(String str, String key) { //str是整串,key是要查找的子串
int count = 0; //重置计数器
int index = 0; //字符串下标
while((index = str.indexOf(key,index))!=-1) //如果返回的下标不是-1 就继续查找子串
{
index += key.length(); //不断更新最近一次查到子串的下标,并将它加上子串长度
count++; //子串数目自加
}
return count;
}
public static void main(String[] args)
{
String str = "cr7goalx3wowcr7cr9ohcr7goalx1wowcr7goalx2cr7goalx2kingcr7goalx1biucr7goalx3woooowcr7goalx2"; //8个cr7
String key = "cr7";
int count = 0;
count = getKeyCount(str,key);
System.out.println("count="+count);
}
结果:
count=8
------------