Im practicing recursion for my own amusement using the codingBat exercises. Im doing this exercise:
Given a string, compute recursively the number of times lowercase "hi" appears in the string, however do not count "hi" that have an 'x' immedately before them.
countHi2("ahixhi") → 1
countHi2("ahibhi") → 2
countHi2("xhixhi") → 0
I tried to do this code but it keep throwing out of bounds exception:
public int countHi2(String str){
if(str.length()<2){
return 0;
}
else if(str.substring(0,3).equals("xhi")){
return countHi2(str.substring(3));
}
else if(str.substring(0,2).equals("hi")){
return 1+countHi2(str.substring(2));
}
else{
return countHi2(str.substring(1));
}
}
I changed the substring() and equals to startsWith()
else if(str.startsWith("xhi")){
return countHi2(str.substring(3));
And now works perfectly, can someone please point out why my first code wasnt correct? Is there a difference between startsWith() and equals()?