Stack Overflow archive
2 score

Recursion to find the number of occurrences of a specified character in a string

score
2
question views
13.8K
license
CC BY-SA 3.0

The other answers are correct; you need to check the length of the string before calling str.substring(1). However, you don't need another method to maintain the ct variable. Here is a Java 101 appropriate answer:

java
import java.util.Scanner;

public class Exercise18_10 {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Please enter a word: ");
    String word = input.next();
    System.out.print("Please enter a character: ");
    char c = input.next().charAt(0);
    int count = count(word, c);
    System.out.println(String.format("%d occurrences of %c in '%s'", count, c, word));
  }

  public static int count(String str, char a) {
    if (str.length() == 0) {
      return 0;
    }
    int count = 0;
    if (str.charAt(0) == a) {
      count++;
    }
    return count + count(str.substring(1), a);
  }


}

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.