【发布时间】: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();