Using recursion to find a character in a string

前端 未结 6 2102
囚心锁ツ
囚心锁ツ 2021-01-20 00:35

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          


        
6条回答
  •  别那么骄傲
    2021-01-20 01:27

    Here's another variation. Instead of calling substring you could modify the function a bit to pass the next index to check. Notice that the recursion is initiated with index 0. (You could actually start on any index. There is also some error checking in case the letter isn't found. Looking for x in apple will return -1.)

    public static void main(String []args){  
        System.out.println("Index: " + indexOf('e', "apple", 0));
        System.out.println("Index: " + indexOf('x', "apple", 0));
        System.out.println("Index: " + indexOf('p', "Mississippi", 3));
        System.out.println("Index: " + indexOf('p', "Mississippi", 908));
    }
    
    public static int indexOf(char ch, String str, int idx) {
        // check for garbage data and incorrect indices
        if (str == null || str.equals("") || idx > str.length()-1) 
            return -1;
    
        // check to see if we meet our condition
        if (ch == str.charAt(idx)) 
            return idx;
    
        // we don't match so we recurse to check the next character
        return indexOf(ch, str, idx+1);
    }
    

    Output:

    Index: 4
    Index: -1
    Index: 8
    Index: -1
    

提交回复
热议问题