Count occurrences of a given character in a String in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
private static int countOccurrences(String str, char ch) { int counter = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ch) { counter++; } } return counter; } |
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:
|
1 2 3 4 5 |
private static long countOccurrences(String str, char ch) { return str.chars() .filter(c -> c == ch) .count(); } |
3. Using Guava Library
Another good alternative is to use Guava’s CharMatcher class.
|
1 2 3 |
private static int countOccurrences(String str, char ch) { return com.google.common.base.CharMatcher.is(ch).countIn(str); } |
4. Using Apache Commons Lang
We can also achieve this using the countMatches method from the StringUtils class provided by the Apache Commons library.
|
1 2 3 |
private static int countOccurrences(String str, char ch) { return org.apache.commons.lang3.StringUtils.countMatches(str, String.valueOf(ch)); } |
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:
|
1 2 3 |
private static int countOccurrences(String str, char ch) { return str.length() - str.replace(String.valueOf(ch), "").length(); } |
6. Using Regex
Another plausible way is using regular expressions along with a counter.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
private static int countOccurrences(String str, char ch) { Matcher matcher = Pattern.compile(String.valueOf(ch)) .matcher(str); int counter = 0; while (matcher.find()) { counter++; } return counter; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.util.HashMap; import java.util.Map; class Main { private static Map<Character, Integer> constructFrequencyMap(char[] chars) { Map<Character, Integer> freq = new HashMap<>(); for (char ch: chars) { freq.put(ch, freq.getOrDefault(ch, 0) + 1); } return freq; } private static int countOccurrences(Map<Character, Integer> freq, char ch) { return freq.get(ch); } public static void main(String[] args) { String str = "ABAACBDD"; char ch = 'A'; Map<Character, Integer> freq = constructFrequencyMap(str.toCharArray()); System.out.println("Character " + ch + " occurs " + countOccurrences(freq, ch) + " times."); } } |
That’s all about counting occurrences of a given character in a Java String.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)