Count Occurrences of a Char in a String

1. Overview

There are many ways to count the number of occurrences of a char in a String in Java.

In this quick tutorial, we’ll focus on a few examples of how to count characters — first with the core Java library and then with other libraries and frameworks such as Spring and Guava.

2. Using Core Java Lib

2.1. Imperative Approach

Some developers may prefer to use core Java. There are many ways for counting the number of occurrences of a char in a String.

Let’s start with a simple/naive approach:

String someString = "elephant";
char someChar = 'e';
int count = 0;
 
for (int i = 0; i < someString.length(); i++) {
    if (someString.charAt(i) == someChar) {
        count++;
    }
}
assertEquals(2, count);

Not surprisingly, this will work, but there are better ways to do this.

2.2. Using Recursion

A less obvious but still interesting solution is to use recursion:

private static int countOccurences(
  String someString, char searchedChar, int index) {
    if (index >= someString.length()) {
        return 0;
    }
    
    int count = someString.charAt(index) == searchedChar ? 1 : 0;
    return count + countOccurences(
      someString, searchedChar, index + 1);
}

We can invoke this recursive method in the following way: useRecursionToCountChars(“elephant”, ‘e’, 0).

2.3. Using Regular Expressions

Another way would be to use regular expressions:

Pattern pattern = Pattern.compile("[^e]*e");
Matcher matcher = pattern.matcher("elephant");
int count = 0;
while (matcher.find()) {
    count++;
}
 
assertEquals(2, count);

Just note that this solution is technically correct but sub-optimal, as it’s overkill to use the very powerful regular expressions to solve such a simple problem as finding the number of occurrences of a character in a string.

2.4. Using Java 8 Features

New features available in Java 8 can be very helpful here.

Let’s use streams and lambdas to implement the count:

String someString = "elephant";
long count = someString.chars().filter(ch -> ch == 'e').count();
assertEquals(2, count);

long count2 = someString.codePoints().filter(ch -> ch == 'e').count();
assertEquals(2, count2);

So, this is clearly a cleaner and more readable solution using the core library.

3. Using External Libraries

Let’s now look at a few solutions that make use of utilities from external libraries.

3.1. Using StringUtils

In general, it is always better to use an existing solution instead of inventing our own. The commons.lang.StringUtils class provides us with the countMatches() method, which can be used for counting chars or even sub-strings in given String.

First, we need to include the appropriate dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.11</version>
</dependency>

We can find the latest version on Maven Central.

Let’s now use countMatches() to count the number of e characters in the “elephant” String literal:

int count = StringUtils.countMatches("elephant", "e");
assertEquals(2, count);

3.2. Using Guava

Guava can also be helpful in counting chars. We need to define the dependency:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>21.0</version>
</dependency>

We can find the latest version on Maven Central.

Let’s see how Guava can quickly help us to count chars:

int count = CharMatcher.is('e').countIn("elephant");
assertEquals(2, count);

3.3. Using Spring

Naturally, adding the Spring Framework into our project just to count chars doesn’t make sense.

However, if we already have it in our project, we just need to use the countOccurencesOf() method:

int count = StringUtils.countOccurrencesOf("elephant", "e");
assertEquals(2, count);

4. Conclusion

In this article, we focused on various ways to count chars in the String. Some of them were designed purely in Java; some required additional libraries.

Our recommendation is to use already existing utilities from StringUtils, Guava or Spring. However, this article offers some possibilities to get it done with Java 8 if using only plain Java is preferred.

The complete source code for these examples is available in this GitHub project.

Related posts:

A Guide to LinkedHashMap in Java
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Java Program to Find ith Largest Number from a Given List Using Order-Statistic Algorithm
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Handle EML file with JavaMail
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Java Program to Perform Sorting Using B-Tree
Spring Boot - Creating Docker Image
Check if a String is a Palindrome in Java
Java Program to Find Inverse of a Matrix
Python String lower()
Hướng dẫn Java Design Pattern – Builder
HttpClient Basic Authentication
Java Program to Check whether Graph is a Bipartite using BFS
Java Program to Implement Cartesian Tree
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
How to Get the Last Element of a Stream in Java?
File Upload with Spring MVC
Convert Hex to ASCII in Java
Java Byte Array to InputStream
The Difference Between Collection.stream().forEach() and Collection.forEach()
Java Program to Implement Heap’s Algorithm for Permutation of N Numbers
What is Thread-Safety and How to Achieve it?
Java Program to Perform Insertion in a 2 Dimension K-D Tree
Biến trong java
Java Program to Check Cycle in a Graph using Topological Sort
Constructor Injection in Spring with Lombok
Hướng dẫn Java Design Pattern – Prototype
Java Program to Implement Heap
Introduction to Spring Cloud CLI
Spring MVC Custom Validation