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 < 10
i.e. 0 to 9
, the teststr.charAt(i+3)=='e'
will causei + 3
to exceed the length of the string wheni >= 7
, and throw an exception. By limitingi
to3 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.e
where.
matches any character. The-1
will ensure trailing empty strings will be preserved (in case the string ends withcodecodecode
So the number array size would be1 + the number of delimiters encountered
so subtracting one is required.Since
split
takes a regex, eithercode
orco.e
can be used.Updated
Better still would be to use Andy Turner's suggestion and increment do
i += 3
when docode++
count.