本人初学java,仅根据所学知识总结了几个方法。
1.方法一:直接法
通过indexOf()寻找指定字符串,截取指定字符串后面的部分,再次寻找,直到找完所有
public void countString(String str,String s) {
int count = 0,len = str.length();
while(str.indexOf(s) != -1) {
str = str.substring(str.indexOf(s) + 1,str.length());
count++;
}
System.out.println("此字符串有" + count + "个" + s);
}
2.方法二:间接法
将源字符串中的指定字符串用空替换,存到另一个字符串中,两者长度相减再除去指定字符串长度
public void countString(String str,String s) {
String str1 = str.replaceAll(s, "");
int len1 = str.length(),len2 = str1.length(),len3 = s.length();
int count = (len1 - len2) / len3;
System.out.println("此字符串有" + count + "个" + s);
}
3.方法三:使用集合
可以指定字符串和对应次数存入Map集合中,但不需要这么麻烦,此处略去
现在再看觉得好像没有必要。。。。orz
但写都写了,发出去算了
本文分享了三种在Java中计算特定子字符串出现次数的方法:直接法、间接法和使用集合法。直接法利用indexOf()进行逐次查找;间接法则通过replaceAll()替换后比较长度;集合法虽提及但未详述。
543

被折叠的 条评论
为什么被折叠?



