next up previous
Next: Example: maximum of positive Up: Unit 11 Previous: Comparison between recursion and

Example: number of occurrences of a character in a string

Recursive characterization of the operation of counting the occurrences of the character c in the string s:

Implementation:

public static int countChars(String s, char c) {
  if (s.length() == 0)
    return 0;
  else if (s.charAt(0) == c)
    return 1 + countChars(s.substring(1), c);
  else
    return countChars(s.substring(1), c);
}


next up previous
Next: Example: maximum of positive Up: Unit 11 Previous: Comparison between recursion and