I’m learning Java as I complete CodingBat exercises, and I want to start using regular expressions to solve some level 2 String problems. 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.
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.
Try using this in the if statement. Unless I’m mixing up Java rules with PHP, then it needs to be +4 rather than +3.