首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

求助 怎么得到 一个字符串所含另一个子串的个数

2011-12-23 
求助 如何得到 一个字符串所含另一个子串的个数比如,str1acdacdyyyojoacdadd 中含有acd的个数,结果应该

求助 如何得到 一个字符串所含另一个子串的个数
比如,
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;
}

热点排行