public int countCode(String str) {
int code = 0;
for(int i=0; i<str.length()-3; i++){
if(str.substring(i, i+2).equals("co") && str.charAt(i+3)=='e'){
code++;
}
}
return code;
}
Hi guys, I've solved this problem by some help among the internet. But the actual problem that I'm facing is this, (str.length()-3) in the for loop. I don't understand why the str.length()-3 having this -3 in it. please explain it...
Assume String is length
10. When I goes from0 to < 10i.e. 0 to 9, the teststr.charAt(i+3)=='e'will causei + 3to exceed the length of the string wheni >= 7, and throw an exception. By limitingito3 less than the length, the loop will terminate before the index goes out of bounds.Regarding your solution, I would offer the following alternative.
split("co.e",-1)will split on the wordco.ewhere.matches any character. The-1will ensure trailing empty strings will be preserved (in case the string ends withcodecodecodeSo the number array size would be1 + the number of delimiters encounteredso subtracting one is required.Since
splittakes a regex, eithercodeorco.ecan be used.Updated
Better still would be to use Andy Turner's suggestion and increment do
i += 3when docode++count.