Search code examples
javastringcountcharuppercase

count uppercase chars in string recursively


I have to solve an exercise, counting all the uppercase chars in a String - recursively - Anyhow I thought I might have found a solution - but it won't work… Probably you might help me? Thanks!

public static int CountCapitals(String s) {
    int counter = 0;
    // if (Character.isUpperCase(s.charAt(0)))counter+=1;
    if (s.length() == 0)
        return counter;
    if (s.length() == 1 && s.charAt(0) < 65 && s.charAt(0) > 90)
        return 0;
    if (s.charAt(0) < 'A' && s.charAt(0) > 'Z') {
        return CountCapitals(s.substring(1));
    } 
    if (s.charAt(0) >= 'A' && s.charAt(0) <= 'Z')
        counter++;
        return CountCapitals(s.substring(1));
}

Solution

  • The problem with your code is the use of counter: each level of invocation has its own counter, initially set to zero. The ++ operator at the bottom has no effect.

    You need to compute the result of this invocation based on the result of the previous invocation. Your base case (i.e. s.length() == 0) is fine; the rest of your code needs to change so that it returns whatever CountCapitals(s.substring(1)) when the first letter is non-capital; when the first letter is capital, your function should return 1 + CountCapitals(s.substring(1)).