用java 正则表达式 计算一个字符串中某个子串的个数

怎么计算出"abcdfdfsabcdfdsf abc fdfdabc" 这个字符串中abc的个数??

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTest {

public static void main(String args[]){
String str = "abcdfdfsabcdfdsf abc fdfdabcabc";

//1. 用这则表达式处理, 不过好像一点都不省事..
Pattern p = Pattern.compile("abc",Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
int count = 0;
while(m.find()){
count ++;
}
System.out.println("ABC的个数 : " + count);

//2. 用普通方法来做,比较省事
String [] ary = ("," + str + ",").split("abc");
System.out.println("ABC的个数 : " + (ary.length - 1));
}
}

我觉得用split方法,以"abc"做分隔符将字串拆分成数组,这样比较简单.不过上面的代码(第二种方法)只能判断小写"abc"的个数, 如果你还需要将"ABC"或者"aBc"或者"abC"这样的字串都找出来, 只需要将第二种方法的代码修改成下面这样的就可以了:

String [] ary = ("," + str.toLowerCase() + ",").split("abc");
System.out.println("ABC的个数 : " + (ary.length - 1));
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-08-13
public class Test1{
public static void main(String[] args){
String str = "abcdfdfsabcdfdsf abc fdfdabc";
int count = 0;
for(int i=0; i<str.length(); i++){
int n = str.indexOf("abc",i);//从i位置搜索“abc”,返回第一次出现的位置
if(n == i) count++;//如果返回的位置和开始搜索的位置相同,说明又出现了一次,计数器加一
}
System.out.println(count);
}
}//到API里查下,会有更好的方法,呵呵
第2个回答  2009-08-12
只要匹配一个 abcd ,那么就可以得到这个 abcd 的位置,再把原来的母串分割掉前面的 abcd,如第一个 abcd 查到后就可以得到 fdfsabcdfdsf abc fdfdabc子串,再把这个子串拿来比对,如此下去直到搜不到 abcd 为止。。。
相似回答