How do I count the number of occurrences of a char in a String?

Here is one way you could do it in Java:

public static int countChar(String str, char c) {
    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == c) {
            count++;
        }
    }
    return count;
}

You can use this method like this:

String str = "hello";
char c = 'l';
int count = countChar(str, c);

This will set count to 2, because there are two occurrences of 'l' in "hello".

Alternatively, you could use the String.replace() method to remove all occurrences of the specified character from the string, and then get the length of the modified string. The number of occurrences of the character would be the difference between the length of the original string and the modified string.

Here's an example of how you could do this:

public static int countChar(String str, char c) {
    String modifiedStr = str.replace(String.valueOf(c), "");
    return str.length() - modifiedStr.length();
}

This method works by replacing all occurrences of c with an empty string, effectively removing them from the string. The number of occurrences is then calculated by subtracting the length of the modified string from the length of the original string.