Using recursion to find a character in a string

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

    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);
    
    }}
    

提交回复
热议问题