public class StringTest3
{
public static void main(String [] args)
{
String whole ="abcnabcmabceswdbca abc dfr afc";
String son = "abc";
int ct = count1(whole, son);
System.out.println(ct);
int ct2 = count2(whole, son);
System.out.println(ct2);
}
// 这种方法是通过获得一次后截取字符串
public static int count1(String whole,String son)
{
int index = 0;
int count = 0;
while((index=whole.indexOf(son))!=-1)
{
whole=whole.substring(index+son.length());
++count;
}
return count;
}
// 这种方法是通过移动检索的角标(个人建议用这种,尤其是大篇幅的统计出现次数时候)
public static int count2(String whole,String son)
{
int index = 0;
int count = 0;
while((index=whole.indexOf(son,index))!=-1)
{
index = index + son.length();
++count;
}
return count;
}
}
————————————————
版权声明:本文为CSDN博主「明明如月学长」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/w605283073/article/details/46572565