Java String Program · S23
Count Substring Occurrences in Java
Find a substring, count it, then continue searching after the match. Where you resume decides whether overlapping matches are counted.
Problem Statement
Write a method that counts how many times a substring occurs in a text without overlapping: after a match, the search continues after the end of that match.
If the substring is empty, the method returns 0.
Input/Output Examples
"banana", "ana"Output1Explanation: after the match at index 1, the next search starts at index 4, where only "na" is left."aaaa", "aa"Output2Explanation: matches at indexes 0 and 2 do not overlap."hello", "xyz"Output0Explanation: the substring never occurs.Visual Explanation
"ana" in "banana": the match at index 1 (purple) is counted, and the search resumes at index 4, past the match.Resuming at match + sub.length() is what prevents overlap. Resuming at match + 1 instead would also find the overlapping match at index 3 and return 2.
Approaches
Both approaches skip past each match. The first relies on indexOf(); the second tests each position with startsWith().
Approach 1: indexOf() Loop (Recommended)
Idea: call indexOf(sub, from) repeatedly, moving from past each match.
- Return 0 for an empty substring.
- Find the first match with
indexOf(sub). - While a match exists, count it and search again from
match + sub.length().
Time: O(n × m) · Space: O(1).
Approach 2: startsWith() at Each Position
Idea: walk through the text; at each index, check startsWith(sub, i) and jump past a match.
- Return 0 for an empty substring.
- For each
iup ton - m, testtext.startsWith(sub, i). - On a match, count it and add
mtoi; otherwise add 1.
Time: O(n × m) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: indexOf() Loop (Recommended)
indexOf() is heavily optimised in the JDK, so this is fast in practice.
public class SubstringCountIndexOf {
// After each match, the search continues after the match, so matches never overlap
static int countOccurrences(String text, String sub) {
if (sub.isEmpty()) {
return 0;
}
int count = 0;
int from = text.indexOf(sub);
while (from != -1) {
count++;
from = text.indexOf(sub, from + sub.length());
}
return count;
}
public static void main(String[] args) {
String[][] cases = {{"banana", "ana"}, {"aaaa", "aa"}, {"hello", "xyz"}};
for (String[] c : cases) {
System.out.println("\"" + c[0] + "\", \"" + c[1] + "\" -> " + countOccurrences(c[0], c[1]));
}
}
}
"banana", "ana" -> 1 "aaaa", "aa" -> 2 "hello", "xyz" -> 0
Time complexity: O(n × m) · Space complexity: O(1).
Approach 2: startsWith() at Each Position
The loop makes the overlap rule explicit: the jump size decides it.
public class SubstringCountManual {
// Checks each position with startsWith(); on a match, jumps past it
static int countOccurrences(String text, String sub) {
if (sub.isEmpty()) {
return 0;
}
int count = 0;
int i = 0;
while (i <= text.length() - sub.length()) {
if (text.startsWith(sub, i)) {
count++;
i += sub.length();
} else {
i++;
}
}
return count;
}
public static void main(String[] args) {
String[][] cases = {{"banana", "ana"}, {"aaaa", "aa"}, {"hello", "xyz"}};
for (String[] c : cases) {
System.out.println("\"" + c[0] + "\", \"" + c[1] + "\" -> " + countOccurrences(c[0], c[1]));
}
}
}
"banana", "ana" -> 1 "aaaa", "aa" -> 2 "hello", "xyz" -> 0
Time complexity: O(n × m) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| indexOf() Loop | O(n × m) | O(1) |
| startsWith() at Each Position | O(n × m) | O(1) |
Here n is the length of the text and m is the length of the substring. Each position may need up to m character comparisons; KMP would reduce this to O(n + m).
Interview Tips and Recommended Approach
- Clarify overlap first. For
"aaaa"and"aa", the answer is 2 without overlap and 3 with it. - Guard against an empty substring.
indexOf("")matches at every position, so the loop would never end. - Avoid the split trick.
text.split(sub).length - 1fails when the match is at the end and treatssubas a regex. - Know the regex alternative:
Pattern.compile(Pattern.quote(sub)).matcher(text)with afind()loop also counts non-overlapping matches.
Recommended Approach: indexOf() Loop
Why: it uses the JDK's optimised search, makes the non-overlap rule a single expression and needs no extra memory.