我在完成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;
}
我想,也許比賽方法與子串不兼容,但我不確定。
[檢查文檔](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#matches(java.lang中。字符串))它確實需要一個正則表達式 – 2012-08-13 16:06:45
http://www.regular-expressions.info/tutorial.html是篦地方學習正則表達式 – Pshemo 2012-08-13 16:08:07
'「co?e」'意味着我期望字母c,其次可能是o ,也許不是,接着是e。它只會匹配「coe」和「ce」 – 2012-08-13 16:08:36