Using recursion to find a character in a string

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

    first of all : Recursion has two pillars, Base Case and General Case.

    Base Case (the termination point) is the one where Recursion terminates and General Case as the name implies is where the program keeps executing until it finds Base Case

    you may try this example, where count is a global static variable

    public static int indexOf(char ch, String str)
    {
      // Returns the index of the of the character ch
      if (str == null || str.Equals(""))     //Base Case
      {
         if (count != 0)
         {
            if(str.Length == 0)
               return -1;  
            return count;
         }
         else
            return -1;          
      }
      else if (ch == str.CharAt(0))          //Base Case  
         return 1 + count; 
      count++;
      return indexOf(ch, str.Substring(1));  //General Case
    }
    

提交回复
热议问题