Using recursion to find a character in a string

前端 未结 6 2168
囚心锁ツ
囚心锁ツ 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:15

    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
    

提交回复
热议问题