在java中查找字符串中的字符串序列数

时间:2013-11-17 13:22:15

标签: java string

      class Plan{ 
    String str;
    String findstring;
      public void countsubString(String str,String findString){
    int count=0;
    for(int i=0;i<str.length();i++){
    if(str.contains(findString)){ 
        count++;
     }
    }
    System.out.println(count);
 }   
  public static void main(String args[]) throws IOException{  
     Plan b=new Plan(); 
     System.out.println("Enter the string..");
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String str=br.readLine();
      BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
    String findstring=br1.readLine();
      b.countsubString(str, findstring);
}    
}

我有一头牛哇牛哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇

3 个答案:

答案 0 :(得分:2)

而不是以下代码:

for(int i=0;i< ;i++){
if(str.contains(findString)){ 
    count++;
 }
}

使用以下内容:

int lastIndex = 0;
while(lastIndex != -1){

       lastIndex = str.indexOf(findString,lastIndex);

       if( lastIndex != -1){
             count ++;
             lastIndex+=findString.length();
      }
}

答案 1 :(得分:2)

使用正则表达式进行群组捕获。更高效,可读和更少的代码。

        String str = "cow wow wow cow cow wow wow";
        Matcher cowMatcher = Pattern.compile("(.*?cow)")
                .matcher(
                    str);
        int count=0;

        while (cowMatcher.find()) {
        ++count;
    }

答案 2 :(得分:0)

contains是不正确的方法。使用equals,如下所示

public void countsubString(String str,String findString){
    int count=0;
    String strArr[]=str.split(" +");
    for(String str: strArr){
    if(str.equals(findString)){ 
        count++;
     }
    }
    System.out.println(count);
 }