当前位置: 代码迷 >> J2SE >> 如何显示字符串在另一个字符串中出现的次数
  详细解决方案

如何显示字符串在另一个字符串中出现的次数

热度:101   发布时间:2016-04-24 13:14:49.0
怎么显示字符串在另一个字符串中出现的次数
比如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;    }}
  相关解决方案