Noob
Noob

Reputation: 534

Recursively finding number of letter occurences in a string

Hi im trying to create a recursive method that returns the amount of times a character exists within a word. So far I have created a method that achieves this non-recursively, but Im having trouble thinking about how to do it recursively.

public static int count (String line, char c)
{
     int charOccurences = 0;
     for (int x = 0 ; x < line.length () ; x++)
     {
         if (line.charAt (x) == c)
         {
             charOccurences++;
         }
     }
     return charOccurences;       
}

Any help would be great, thanks.

Upvotes: 0

Views: 95

Answers (1)

John Yost
John Yost

Reputation: 693

You're missing some logic here.

  • If you run out of characters 'c' then lastIndexOf returns -1 which will cause errors in the substring method.
  • You need some logic to tally the occurrences of c. Your recursion still has to add up the return values of your calls to 'count' or the number of times you call count. Currently the last call to count is going to return 0 which will just get passed back.

This sounds like a homework problem so I'm going to let someone else do your homework for you :)

Good luck!

Upvotes: 3

Related Questions