This post will discuss how to count occurrences of a given character in a string in Java.

1. Naive solution

We can also write our own routine for this simple task. The idea is to iterate over characters in the string using a for-loop, and for each encountered character, increment the counter (starting from 0) if it matches with the given character.

Download  Run Code

2. Using Java 8

With Java 8, we can use Stream to count occurrences of the given character in a string. This is demonstrated below:

Download  Run Code

3. Using Guava Library

Another good alternative is to use Guava’s CharMatcher class.

Download Code

4. Using Apache Commons Lang

We can also achieve this using the countMatches method from the StringUtils class provided by the Apache Commons library.

Download Code

5. Using replace() method

Here’s another solution that uses String’s replace() method to remove all occurrences of the specified character from the string and make use of the length() property of the string to determine the count, as shown below:

Download  Run Code

6. Using Regex

Another plausible way is using regular expressions along with a counter.

Download  Run Code

7. Using Frequency Map

The time complexity of all the above solutions is at-least linear since we’re scanning the whole string. If the total number of lookups is more, consider pre-processing the string once and create a frequency map out of it that stores the count of each distinct character present in the string. Now each subsequent method call will take the only constant line.

Download  Run Code

That’s all about counting occurrences of a given character in a Java String.