简体   繁体   中英

Regular Expressions to count number of ocurrences of a string in Java

I'm learning Java as I complete CodingBat exercises, and I want to start using regular expressions to solve some level 2 String problems. I'm currently trying to solve this problem:

Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.

countCode("aaacodebbb") → 1
countCode("codexxcode") → 2
countCode("cozexxcope") → 2

And here is the piece of code I wrote (which doesn't work, and I'd like to know why):

public int countCode(String str) {
 int counter = 0;

 for (int i=0; i<str.length()-2; i++)
       if (str.substring(i, i+3).matches("co?e"))
        counter++;

 return counter;
}

I'm thinking that maybe the matches method isn't compatible with substring, but I'm not sure.

You need to use the regular expression syntax. In this case you want "co\\\\we" , where \\\\w means any letter.

BTW you can do

public static int countCode(String str) {
    return str.split("co\\we", -1).length - 1;
}

Try using this in the if statement. Unless I'm mixing up Java rules with PHP, then it needs to be +4 rather than +3.

str.substring(i, i+4)
public int countCode(String str) {
  int count=0;             // created a variable to count the appearance of "coe" in the string because d doesn't matter. 
  for(int i=0;i<str.length()-3;i++){
    if(str.charAt(i)=='c'&&str.charAt(i+1)=='o'&&str.charAt(i+3)=='e'){
      ++count;                       // increment count if we found 'c' and 'o' and 'e' in the string.

    }
  }
  return count;       // returing the number of count 'c','o','e' appeared in string.
}
public class MyClass {

    public static void main(String[] args) {

      String str="Ramcodecopecofeacolecopecofeghfgjkfjfkjjcojecjcj BY HARSH RAJ";
      int count=0;

      for (int i = 0; i < str.length()-3; i++) {
          if((str.substring(i, i+4)).matches("co[\\w]e")){
                count++;

          }
      }
      System.out.println(count);
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM