Count Sequence Occurrences in a Java String
In Java programming, it is common to encounter scenarios where we need to count how many times a specific sequence of characters occurs in a string. Let us delve into understanding how to count occurrences of a specific sequence in a Java String using different approaches.
1. Problem Overview
Suppose we have a string text and a sequence sequence. We want to count how many times sequence appears in text. For example:
String text = "hellohellohello"; String sequence = "hello";
The output should be 3 because “hello” appears three times.
2. Code Example
The following Java program illustrates five different ways to count the number of times a sequence appears in a string. It uses both standard and external dependencies. The java.util.regex package provides the Pattern and Matcher classes for performing regular expression-based string searches, while the java.util.stream package allows processing match results as streams (available in Java 9 and above). Additionally, org.apache.commons.lang3.StringUtils from the Apache Commons Lang library offers convenient string utility methods, including countMatches(). To use StringUtils, ensure that the Apache Commons Lang library is added to the project dependencies (pom.xml or build.gradle file).
import java.util.regex.*;
import java.util.stream.*;
import org.apache.commons.lang3.StringUtils;
public class CountSequenceInString {
public static void main(String[] args) {
String text = "hellohellohello";
String sequence = "hello";
System.out.println("Text: " + text);
System.out.println("Sequence: " + sequence);
System.out.println();
// 1. Using indexOf() in a loop
int countIndexOf = 0;
int index = 0;
while ((index = text.indexOf(sequence, index)) != -1) {
countIndexOf++;
index += sequence.length();
}
System.out.println("Occurrences using indexOf(): " + countIndexOf);
// 2. Using Regex with Matcher.find()
Pattern pattern = Pattern.compile(Pattern.quote(sequence));
Matcher matcher = pattern.matcher(text);
int countMatcherFind = 0;
while (matcher.find()) {
countMatcherFind++;
}
System.out.println("Occurrences using Matcher.find(): " + countMatcherFind);
// 3. Using Regex with split()
String[] parts = text.split(Pattern.quote(sequence));
int countSplit = parts.length - 1;
System.out.println("Occurrences using split(): " + countSplit);
// 4. Using Streams with Matcher.results() (Java 9+)
matcher = pattern.matcher(text); // reset matcher
long countStream = matcher.results().count();
System.out.println("Occurrences using Matcher.results() stream: " + countStream);
// 5. Using Apache Commons Lang StringUtils
int countStringUtils = StringUtils.countMatches(text, sequence);
System.out.println("Occurrences using StringUtils.countMatches(): " + countStringUtils);
}
}
2.1 Code Explanation
The program CountSequenceInString demonstrates five different ways to count how many times a sequence appears in a given string. It starts by defining text = "hellohellohello" and sequence = "hello", then prints them for clarity. The first approach uses indexOf() inside a loop, repeatedly searching for the sequence and moving the index forward by the sequence length after each match, producing a count of 3. The second approach uses regular expressions with Pattern and Matcher.find(), where each successful match increments the counter, again yielding 3. The third method uses split() with Pattern.quote(), which splits the string wherever the sequence appears; the number of occurrences is the length of the resulting array minus one. The fourth approach, available in Java 9+, leverages Matcher.results() to return a stream of matches and then counts them directly. Finally, the fifth approach uses StringUtils.countMatches() from Apache Commons Lang, providing the cleanest one-liner solution. All five techniques correctly output 3, since the substring "hello" appears exactly three times in "hellohellohello".
2.2 Code Output
When run, the program produces the following output:
Text: hellohellohello Sequence: hello Occurrences using indexOf(): 3 Occurrences using Matcher.find(): 3 Occurrences using split(): 3 Occurrences using Matcher.results() stream: 3 Occurrences using StringUtils.countMatches(): 3
3. Conclusion
Counting occurrences of a sequence in a Java string can be achieved using multiple approaches. The indexOf() loop method works in all Java versions, regex provides flexibility, streams simplify modern Java, and libraries like Apache Commons Lang offer ready-made solutions. Choosing the right approach depends on your specific use case and project requirements.






