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()?
First you make sure the string has at least 2 characters in it, then you test if the first three characters are xhi
. String.substr
throws an exception if the string is not long enough.
String.startsWith
doesn't have this problem, it doesn't throw an exception when you check whether a 2 character string starts with 3 characters - it just returns false
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.