Construct0r Construct0r - 1 month ago 9
Java Question

Return the number of times hi appears

I'm doing some coding bat exercises and I don't quite understand what's going on inside the for-loop.

public static int countHi(String str){
int count = 0;

// While i is less than the length of string increase the index by one
// Checking the char at each index
for(int i = 0; i < str.length()-1; i++){
// Do i + 2 because hi has two letters
// i = index 0 and add 2 so 0,1,2-- but 2 is exlcuded so check to see if index 0,1 equals "hi"
if(str.substring(i, i+2).equals("hi")){
count++;
}
}
System.out.println("Hi appears: " + count + " times.");
return count;
}


Why is it str.length()-1? If I changed that to just str.Length I get an error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5

Answer

Think about this part:

str.substring(i, i+2)

When i is equal to the length of the string, i + 2 will overshoot the end of the string by 1, giving you an out of bounds error.