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

怎么显示字符串在另一个字符串中出现的次数
比如String a="acacacwerwac";
  String b="ac";
显示四

------解决方案--------------------
Java code
System.out.println(a.split(b).length);

------解决方案--------------------
LS是什么答案。。 不管怎么显示都是四。。!!
------解决方案--------------------
[code=Java]
String a = "acacacwerwac ";
String b = "ac ";
int i = 0;

Pattern p = Pattern.compile(b);
Matcher m = p.matcher(a);

while(m.find()){
i++;
}
System.out.println(i);
[/code]
------解决方案--------------------
Java code
public class Test {

    public static void main(String[] args) {
        String a = "acacacwerwac";
        String b = "ac";
        int count = count(a, b);
        System.out.println(count);
    }
    
    private static int count(String src, String find) {
        int count = 0;
        int index = src.indexOf(find); 
        while(index > -1) {
            count++;
            index = src.indexOf(find, index + 1);
        }
        return count;
    }
}