Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:
Count the Number of Times a Sequence Occurs in a Java String
Last updated: September 25, 2025
1. Overview
When working with text in Java, a common requirement is to determine how many times a particular sequence of characters appears in a String. Whether we are analyzing logs, cleaning up text data, or simply validating content, counting substring occurrences is a task that comes up frequently.
In this tutorial, we’ll explore different approaches to solving the problem.
2. Introduction to the Problem
As usual, let’s understand the problem through an example. Let’s say we are given this String:
private final static String INPUT =
"This is a test string. This test is for testing the count of a sequence in a string. This string has three sentences.";
Our goal is to count how many times a given sequence appears in this input String. For example, if we count “string”, the result should be 3. However, if the given sequence is “string.” (with a period), we expect to see 2 as the result.
For simplicity, we’ll skip input validations, such as checking if the input String or the given sequence is null, and so on.
Next, let’s dive into the implementations.
3. Using indexOf() in a Loop
The most straightforward approach is to use the built-in String.indexOf() method. This method returns the index of the first occurrence of a substring.
By repeatedly calling it with a moving starting position, we can count all occurrences:
int countSeqByIndexOf(String input, String seq) {
int count = 0;
int index = input.indexOf(seq);
while (index != -1) {
count++;
index = input.indexOf(seq, index + seq.length());
}
return count;
}
Next, let’s validate this with a unit test:
assertEquals(3, countSeqByIndexOf(INPUT, "string"));
assertEquals(2, countSeqByIndexOf(INPUT, "string."));
As we can see, this approach is efficient and easy to understand.
4. Using Regex with Matcher.find()
For cases where we want more flexibility, regular expressions are an excellent choice. Java’s Pattern and Matcher classes allow us to scan through the input and find matches one by one.
Next, let’s create a solution using the Matcher.find() method:
int countSeqByRegexFind(String input, String seq) {
// Alternative: Pattern pattern = Pattern.compile(seq, Pattern.LITERAL);
Matcher matcher = Pattern.compile(Pattern.quote(seq)).matcher(input)
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
It’s important to note that Pattern.quote(seq) ensures that any special Regex characters in the search sequence are treated literally. In other words, no character in the Regex has special meaning. For example, “string.” literally means a “string” followed by one single period instead of a “string” with any single character.
Alternatively, we can also achieve it by using the Pattern.compile() method with the LITERAL flag. We’ll see this approach in another example soon.
Next, let’s verify if this solution works as expected:
assertEquals(3, countSeqByRegexFind(INPUT, "string"));
assertEquals(2, countSeqByRegexFind(INPUT, "string."));
If we give this test a run, it passes. Therefore, our solution does the job.
5. Using Regex with split()
Another Regex-based approach is to split() the input String by the sequence we want to count. The number of resulting parts minus one gives us the count:
int countSeqByRegexSplit(String input, String seq) {
Pattern pattern = Pattern.compile(seq, Pattern.LITERAL);
return pattern.split(input, -1).length - 1;
}
As we can see, this time, we used Pattern.compile()Â with the LITERAL flag to disable characters’ special meanings in the Regex.
Next, let’s test this approach:
assertEquals(3, countSeqByRegexSplit(INPUT, "string"));
assertEquals(2, countSeqByRegexSplit(INPUT, "string."));
While this method is concise, it may be less intuitive than the Matcher.find() approach. Still, it demonstrates the versatility of Regex in Java.
6. Using Streams with Matcher.results()
With Java 9 or later, we can make use of the Matcher.results() method, which produces a stream of match results. This allows us to leverage the power of Java Streams to count matches elegantly. Let’s look at the implementation:
int countSeqByStream(String input, String seq) {
long count = Pattern.compile(Pattern.quote(seq))
.matcher(input)
.results()
.count();
return Math.toIntExact(count);
}
Next, let’s verify it by a test:
assertEquals(3, countSeqByStream(INPUT, "string"));
assertEquals(2, countSeqByStream(INPUT, "string."));
As we can see, this approach is clean, functional, and integrates nicely with the modern Java API.
7. Using Apache Commons Lang’s StringUtils
Finally, if we already depend on Apache Commons Lang in our project, we can avoid reinventing the wheel by using the StringUtils.countMatches() utility method directly. This one-liner provides a straightforward solution:
assertEquals(3, StringUtils.countMatches(INPUT, "string"));
assertEquals(2, StringUtils.countMatches(INPUT, "string."));
It’s worth mentioning that countMatches()Â uses the indexOf() approach internally:
public static int countMatches(final CharSequence str, final CharSequence sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = CharSequenceUtils.indexOf(str, sub, idx)) != INDEX_NOT_FOUND) {
count++;
idx += sub.length();
}
return count;
}
Apache Commons Lang’s StringUtils.countMatches() is the most concise option to solve our problem, though it requires an external dependency.
8. Conclusion
In this article, we’ve explored multiple ways to count the number of times a sequence occurs in a Java String.
Each method has its strengths, and the choice depends on the context of our project. If performance and simplicity matter, indexOf() is often the best. If we need regex flexibility, Matcher.find() or stream processings shine. And when using external libraries, StringUtils.countMatches() saves us time.
By understanding all these approaches, we are better equipped to pick the right tool for the job whenever we need to count substring occurrences in Java.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
















