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