简体   繁体   English

用于计算Java中字符串出现次数的正则表达式

[英]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. 我在完成CodingBat练习时正在学习Java,并且我想开始使用正则表达式来解决一些2级字符串问题。 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. 返回字符串“ code”出现在给定字符串中任何地方的次数,除非我们接受“ d”的任何字母,所以“ cope”和“ cooe”计数。

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. 我在想,matches方法可能与子字符串不兼容,但我不确定。

You need to use the regular expression syntax. 您需要使用正则表达式语法。 In this case you want "co\\\\we" , where \\\\w means any letter. 在这种情况下,您需要"co\\\\we" ,其中\\\\w表示任何字母。

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. 尝试在if语句中使用它。 Unless I'm mixing up Java rules with PHP, then it needs to be +4 rather than +3. 除非我将Java规则与PHP混为一谈,否则它必须为+4而不是+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);
    }   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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