package com.baidu.sep; //统计字串在整个字符串中出现的次数
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; }
}
原文链接:https://blog.csdn.net/w605283073/article/details/46572565
本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。
还没有人抢沙发呢~