Find the amount of occurances of a character in a string recursively (java)

bughunter :

I am trying to write a method which returns the number of times the first character of a string appears throughout the string. This is what I have so far,

public int numberOfFirstChar0(String str) {
    char ch = str.charAt(0);
    if (str.equals("")) {
        return 0;
    }

    if ((str.substring(0, 1).equals(ch))) {
        return 1 + numberOfFirstChar0(str.substring(1));
    }

    return numberOfFirstChar0(str);
}

however, it does not seem to work (does not return the correct result of how many occurrences there are in the string). Is there anything wrong with the code? Any help is appreciated.

Jason :

This uses 2 functions, one which is recursive. We obtain the character at the first index and the character array from the String once instead of doing it over and over and concatenating the String. We then use recursion to continue going through the indices of the character array.

Why you would do this I have no idea. A simple for-loop would achieve this in a much easier fashion.

    private static int numberOfFirstChar0(String str) {
        if (str.isEmpty()) {
            return 0;
        }
        char[] characters = str.toCharArray();

        char character = characters[0];

        return occurrences(characters, character, 0, 0);
    }

    private static int occurrences(char[] characters, char character, int index, int occurrences) {
        if (index >= characters.length - 1) {
            return occurrences;
        }
        if (characters[index] == character) {
            occurrences++;
        }
        return occurrences(characters, character, ++index, occurrences);
    }

Java 8 Solution

    private static long occurrencesOfFirst(String input) {
        if (input.isEmpty()) {
            return 0;
        }
        char characterAtIndexZero = input.charAt(0);

        return input.chars()
                .filter(character -> character == characterAtIndexZero)
                .count();
    }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=393600&siteId=1
Recommended