Count Occurrences of a Character in Java
A String is simply a sequence of characters. In this tutorial, we will learn the different ways to count the occurrences of a specific character in a String.
Method 1 - Iterative Approach
We will traverse through each character present in the String. If this character matches the one we are looking for, we will increase the count by one. The following code demonstrates this approach.
public static int countChars(String str, char c)
{
int count = 0;
for(int i = 0; i < str.length(); i++)
{
char currChar = str.charAt(i);
if(currChar == c)
count += 1;
}
return count;
}
Let's use this method and check whether it gives desirable output or not.
public static void main(String[] args)
{
String s = "Java is an awesome language!";
int charCountOfA = countChars(s, 'a');
int charCountOfG = countChars(s, 'g');
int charCountOfE = countChars(s, 'e');
System.out.println("The String is: " + s);
System.out.println("Character count of 'a': " + charCountOfA);
System.out.println("Character count of 'g': " + charCountOfG);
System.out.println("Character count of 'e': " + charCountOfE);
}
The String is: Java is an awesome language!
Character count of 'a': 6
Character count of 'g': 2
Character count of 'e': 3
Method 2 - Recursion Approach
Recursion won't be the first thing that comes to mind on seeing this problem. However, we can use recursion to solve this problem. We will use two methods instead of one. The first method will be the recursive one, and the second method invokes the first one. The approach is very similar to the one discussed in the previous section.
public static int countCharsRecur(String str, char c, int idx)
{
if(idx >= str.length())
return 0;
else {
int count = 0;
if(str.charAt(idx) == c)
count = 1;
return count + countCharsRecur(str, c, idx + 1);
}
}
public static int countChars(String s, char c)
{
return countCharsRecur(s, c, 0);
}
Let's use the above methods and view the output.
public static void main(String[] args)
{
String s = "Java is an awesome language!";
int charCountOfA = countChars(s, 'a');
int charCountOfG = countChars(s, 'g');
int charCountOfE = countChars(s, 'e');
System.out.println("The String is: " + s);
System.out.println("Character count of 'a': " + charCountOfA);
System.out.println("Character count of 'g': " + charCountOfG);
System.out.println("Character count of 'e': " + charCountOfE);
}
The String is: Java is an awesome language!
Character count of 'a': 6
Character count of 'g': 2
Character count of 'e': 3
Method 3 - Using Java 8 Streams
Java 8 Streams also provide a simple way to count the occurrences of a character in a String. We will first convert the String to an IntStream by using the chars() method. We can also use the codePoints() method instead of chars(). Next, we will use the filter() method with a Lambda expression to filter out all the matching characters. Finally, we will use the count() method that returns the count of elements in the filtered stream.
public class Demo
{
public static void main(String[] args)
{
String s = "Java is an awesome language!";
int charCountOfA = (int) s.chars().filter(c -> c == 'a').count();
int charCountOfG = (int) s.chars().filter(c -> c == 'g').count();
int charCountOfE = (int) s.chars().filter(c -> c == 'e').count();
System.out.println("The String is: " + s);
System.out.println("Character count of 'a': " + charCountOfA);
System.out.println("Character count of 'g': " + charCountOfG);
System.out.println("Character count of 'e': " + charCountOfE);
}
}
The String is: Java is an awesome language!
Character count of 'a': 6
Character count of 'g': 2
Character count of 'e': 3
Method 4 - Using Regular Expressions
Regular Expressions can also solve this problem. However, it is not a good idea to use regular expressions to solve such a simple problem. The code below demonstrates the use of regex for this problem.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo
{
public static int countChars(String str, char c)
{
String regex = String.valueOf(c);
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
int count = 0;
while(matcher.find())
count += 1;
return count;
}
public static void main(String[] args)
{
String s = "Java is an awesome language!";
int charCountOfA = countChars(s, 'a');
int charCountOfG = countChars(s, 'g');
int charCountOfE = countChars(s, 'e');
System.out.println("The String is: " + s);
System.out.println("Character count of 'a': " + charCountOfA);
System.out.println("Character count of 'g': " + charCountOfG);
System.out.println("Character count of 'e': " + charCountOfE);
}
}
The String is: Java is an awesome language!
Character count of 'a': 6
Character count of 'g': 2
Character count of 'e': 3
Method 5 - External Libraries
Counting occurrences of a character in a String is so common that many external libraries have built-in functions to do this. Let's use a few external libraries to solve this problem.
Using Guava Library
The Guava library provides the CharMatcher class that can count the number of occurrences of a given character. First, we will use the static is() method of this class. This method creates a CharMatcher instance to match a specific char. Next, we will use the countIn() method that takes a string as a parameter and returns the count of the character in that String.
import com.google.common.base.CharMatcher;
public class Demo
{
public static void main(String[] args)
{
String str = "Java is an awesome language!";
CharMatcher cm = CharMatcher.is('a'); //Creating the CharMatcher
int charCountOfA = cm.countIn(str); //Counting the occurences
System.out.println("The String is: " + str);
System.out.println("Character count of 'a': " + charCountOfA);
}
}
The String is: Java is an awesome language!
Character count of 'a': 6
Using Apache Library
The Apache Commons library provides a StringUtils class. This class has a convenient countMatches() method that takes a char and a string as input and returns the count of the character in that String as output.
import org.apache.commons.lang3.StringUtils;
public class Demo
{
public static void main(String[] args)
{
String s = "Java is an awesome language!";
int charCountOfA = StringUtils.countMatches(s, 'a');
int charCountOfG = StringUtils.countMatches(s, 'g');
int charCountOfE = StringUtils.countMatches(s, 'e');
System.out.println("The String is: " + s);
System.out.println("Character count of 'a': " + charCountOfA);
System.out.println("Character count of 'g': " + charCountOfG);
System.out.println("Character count of 'e': " + charCountOfE);
}
}
The String is: Java is an awesome language!
Character count of 'a': 6
Character count of 'g': 2
Character count of 'e': 3
Summary
Counting the occurrences of a character in a String is a pretty simple task. We can use core Java to solve this problem iteratively or recursively. Streams can also solve this problem in a single line of code. We can also use Regular Expressions, but they provide a sub-optimal solution.