Reputation: 21
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...
Upvotes: 1
Views: 141
Reputation: 40057
Assume String is length 10
. When I goes from 0 to < 10
i.e. 0 to 9
, the test str.charAt(i+3)=='e'
will cause i + 3
to exceed the length of the string when i >= 7
, and throw an exception. By limiting i
to 3 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 word co.e
where .
matches any character. The -1
will ensure trailing empty strings will be preserved (in case the string ends with codecodecode
So the number array size would be 1 + the number of delimiters encountered
so subtracting one is required.public static int countCode(String str) {
return (int)str.split("co.e",-1).length-1;
}
Since split
takes a regex, either code
or co.e
can be used.
Updated
Better still would be to use Andy Turner's suggestion and increment do i += 3
when do code++
count.
Upvotes: 0
Reputation: 522719
In the interest of posting an answer which someone might actually use in a production system, we can try a replacement approach:
public int countCode(String str) {
return (str.length() - str.replace("code", "").length()) / 4;
}
Upvotes: 0
Reputation: 1105
Inside the for loop, for any index (i
), it checks that the chars at i
and i+2
and i+3
match your requirements. If your i
becomes length of your string (or last character), then the code will throw exception since it will try to find char
at position which is not really there.
Upvotes: 0