日期:2014-05-20  浏览次数:20617 次

求助 如何得到 一个字符串所含另一个子串的个数
比如,
str1   =   "acdacd   yyyojo   acdadd "
中含有   acd的个数,
结果应该是3。

先谢了,string中找不到相关的方法。


------解决方案--------------------
再修正

if(str.equals(substring))
return 1;
------解决方案--------------------
public static int countMatches(String str, String sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = str.indexOf(sub, idx)) != -1) {
count++;
idx += sub.length();
}
return count;
}

public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}