Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using recursion to find a character in a string

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 of the character ch
public static int indexOf(char ch, String str) {

    if (str == null || str.equals("")) {
        return -1;
    } else if(ch == str.charAt(0)) {
        return 1+ indexOf(ch, str.substring(1));
    }

    return indexOf(ch, str.substring(1));
}

It just doesn't seem to be returning the correct value.

like image 734
user3496026 Avatar asked Jan 11 '23 21:01

user3496026


1 Answers

I'll give you some hints:

  1. When you've found the letter, you don't need to recurse further. Additionally, think about what you should be returning in this case.
  2. When do you recurse, also think about what the function should return.
  3. Is there anything special you need to do if the recursive call returns -1?
like image 165
NPE Avatar answered Jan 18 '23 16:01

NPE