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
Well if we must use recursion then try this:
class RecursiveFirstIndexOf {
public static void main(String[] args) {
System.out.println(indexOf('p', "apple", 0));
}
static int indexOf(char c, String str, int currentIdx) {
if (str == null || str.trim().isEmpty()) {
return -1;
}
return str.charAt(0) == c ? currentIdx : indexOf(c, str.substring(1), ++currentIdx);
}}