【问题标题】:Regular Expressions to count number of ocurrences of a string in Java用于计算 Java 中字符串出现次数的正则表达式
【发布时间】:2012-08-13 16:04:52
【问题描述】:

我在完成 CodingBat 练习时正在学习 Java,我想开始使用正则表达式来解决一些 2 级字符串问题。我目前正在尝试解决这个问题:

返回字符串“code”出现在给定字符串中的任何地方的次数,除了我们将接受任何字母作为“d”,因此“cope”和“cooe”计数。

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

这是我写的一段代码(它不起作用,我想知道为什么):

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;
}

我在想可能 match 方法与子字符串不兼容,但我不确定。

【问题讨论】:

  • Check the docs 它确实需要一个正则表达式
  • regular-expressions.info/tutorial.html 是学习正则表达式的好地方
  • "co?e" 表示我期待字母 c,后跟可能是 o,也可能不是,然后是 e。它只会匹配“coe”和“ce”
  • 我的 1-liner 解决方案:return (str.length() - str.replaceAll("co.e", "").length()) / 4;/4 可以删除:return str.length() - str.replaceAll("co.e", "coe").length();

标签: java regex string


【解决方案1】:

您需要使用正则表达式语法。在这种情况下,您需要"co\\we",其中\\w 表示任何字母。

顺便说一句,你可以做

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

【讨论】:

  • 我会使用\w 而不是.,他指定了字母。
  • 我改了,还是不行,还有什么提示吗?谢谢!
  • 当匹配部分可以放在字符串的末尾时,拆分不是一个好主意
【解决方案2】:

尝试在 if 语句中使用它。除非我将 Java 规则与 PHP 混合,否则它需要是 +4 而不是 +3。

str.substring(i, i+4)

【讨论】:

  • 这是正确的。 OP:s 的原始版本提取了子字符串:“cod”、“coz”和“cop”(以及一堆其他子字符串,但只有这些子字符串应该很有趣)。
  • str.length()-3 在 for 循环部分
【解决方案3】:
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.
}

【讨论】:

    【解决方案4】:
    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);
        }   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-03
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 2015-04-17
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多