java统计一个字符串中某个字符串出现的个数

本人初学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

但写都写了,发出去算了

猜你喜欢

转载自blog.csdn.net/winsumer/article/details/84142702