I am trying to find the first occurrence of a letter in a string. For example, p in apple should return 1. Here is what I have:
// Returns the index of the
Your attempt was good, but not quite there. Here is a correct implementation based off yours:
public static int indexOf(char ch, String str) {
// Returns the index of the of the character ch
if (str == null || str.equals("")) {
// base case: no more string to search; return -1
return -1;
} else if (ch == str.charAt(0)) {
// base case: ch is at the beginning of str; return 0
return 0;
}
// recursive step
int subIndex = indexOf(ch, str.substring(1));
return subIndex == -1 ? -1 : 1 + subIndex;
}
There were two problems with your attempt:
In the else if part, you had found the character, so the right thing to do was stop the recursion, but you were continuing it.
In your last return statement, you needed to be adding 1 to the recursive call (if the character was eventually found), as a way of accumulating the total index number.