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
Why not doing it straight forward?
public static void main(String[] args) {
String str = "abcdef";
for (int idx = 0; idx < str.length(); idx++) {
System.out.printf("Expected %d, found %d\n", idx, indexOf(str.charAt(idx), str, 0));
}
System.out.printf("Expected -1, found %d\n", indexOf(str.charAt(0), null, 0));
}
public static int indexOf(char ch, String str, int index) {
if (str == null || index >= str.length()) return -1;
return str.charAt(index) == ch ? index : indexOf(ch, str, ++index);
}
OUTPUT:
Expected 0, found 0
Expected 1, found 1
Expected 2, found 2
Expected 3, found 3
Expected 4, found 4
Expected 5, found 5
Expected -1, found -1