2012-08-13 22 views
0

我在完成CodingBat練習時正在學習Java,並且我想開始使用正則表達式來解決某些2級String問題。我目前正試圖解決這個問題:用於計算Java中字符串出現次數的正則表達式

返回字符串「代碼」出現在給定字符串中任何地方的次數,除了我們接受任何字母爲'd',所以「應付「和」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; 
} 

我想,也許比賽方法與子串不兼容,但我不確定。

+0

[檢查文檔](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#matches(java.lang中。字符串))它確實需要一個正則表達式 – 2012-08-13 16:06:45

+0

http://www.regular-expressions.info/tutorial.html是篦地方學習正則表達式 – Pshemo 2012-08-13 16:08:07

+3

'「co?e」'意味着我期望字母c,其次可能是o ,也許不是,接着是e。它只會匹配「coe」和「ce」 – 2012-08-13 16:08:36

回答

1

嘗試在if語句用這個。除非我將PHP規則與Java規則混合在一起,否則它必須是+4而不是+3。

str.substring(i, i+4) 
+0

IndexOutOfBoundException – Cristian 2012-08-13 16:12:12

+0

這是正確的。 OP的原始版本提取子字符串:「cod」,「coz」和「cop」(以及其他一些子字符串,但這些是唯一應該感興趣的)。 – Alderath 2012-08-13 16:12:49

+1

for循環部分中的'str.length() - 3' – fvgs 2012-08-13 16:12:53

2

您需要使用正則表達式語法。在這種情況下,您需要"co\\we",其中\\w表示任何字母。

順便說一句,你可以做

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

'我會使用'\ w' '',他指定了字母。 – 2012-08-13 16:08:16

+0

我改變了,仍然無法正常工作,還有其他小費?謝謝! – Cristian 2012-08-13 16:08:17

+0

@DavidB謝謝。 – 2012-08-13 16:09:59

-2
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); 
    } 
} 
0
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. 
} 
相關問題