-1

Code is supposed to do this: 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.

The problem: Ran across Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 11 (line number:10)

public int countCode(String str){
int a = 0; // counter goes thru string
int b = str.length()-1;
int counter = 0; //counts code;
if(str.length() < 4) return 0;
else{
while (a <=b){
if(str.charAt(a) == 'c'){
   if(str.charAt(a+1) == 'o'){
 if(str.charAt(a+3) == 'e'){
   counter++;
    a= a+3;
} // checks e
    else a++;
  } // checks o
  else a++;
} // checks c
else a++;
}

return counter;
}
}

Here's what I tried to evaluate to get said exception:

  • countCode("xxcozeyycop") --> EXPECTED RESULT 1
  • countCode("cozcop") --> EXPECTED RESULT
  • See [this post](http://stackoverflow.com/questions/2635082/java-counting-of-occurrences-of-a-word-in-a-string) – Benvorth Oct 05 '14 at 13:51

3 Answers3

0

Your loop goes from 0 to the length of the string (excluded). But inside the loop, you're doing

str.charAt(a+3)

Obviously, if a is length - 1, a + 3 is length + 2, and you're thus trying to access an element outside the bounds of the string.

Side note: you would understand your own code better if you indented it correctly.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

Instead of

while (a <=b){

use

while (a <= b - 3){

Reason: Your end sign in the while is the condition that the start of the String "code" is inside the String. However, if a = b - 2, then a + 3 = b + 1 = (str.length() - 1 + 1) = str.length() which is just outside the String.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0
public int countCode(String str) {
  int count = 0;
  for(int i = 0; i < str.length()-3; i++)
    if(str.substring(i, i+2).equals("co") && str.charAt(i+3) == 'e')
      count++;

  return count;
}