Count occurrences of a substring in string example shows how to count occurrences of a substring in string in Java using various ways.
How to count occurrences of a substring in string in Java?
There are several ways using which you can count occurrences of a substring in Java.
1) Count occurrence of a substring in a string using the indexOf method
You can count occurrences of a substring in a string using the indexOf method of the String class. Consider below given string.
1 |
String str = "JavaExamplesJavaCodeJavaProgram"; |
Below given is the example program to find the number of occurrences of “Java” within the string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.javacodeexamples.stringexamples; public class CountOccurrencesOfSubstringExample { public static void main(String[] args) { String str = "JavaExamplesJavaCodeJavaProgram"; String strFind = "Java"; int count = 0, fromIndex = 0; while ((fromIndex = str.indexOf(strFind, fromIndex)) != -1 ){ System.out.println("Found at index: " + fromIndex); count++; fromIndex++; } System.out.println("Total occurrences: " + count); } } |
Output
1 2 3 4 |
Found at index: 0 Found at index: 12 Found at index: 20 Total occurrences: 3 |
We started off with having count and fromIndex as 0. fromIndex holds the index position from where we want to search the substring. In the while loop, we find the substring, assign the index of next occurrence to fromIndex and check if the returned value is greater than -1. The indexOf
method returns -1 if the substring is not found in the string, otherwise, it returns the index of the substring.
Inside the while loop, we increment the count of occurrence of substring. We also increment the fromIndex by 1. That is because when we find the substring, next time we want to search the substring after that index. If we don’t do that, we will end up with an infinite loop.
2) Using the split method
You can use the split
method as given below to count the substrings.
1 2 3 4 5 |
String str = "JavaExamplesJavaCodeJavaProgram"; int count = ( str.split("Java", -1).length ) - 1; System.out.println("Total occurrences: " + count); |
Output
1 |
Total occurrences: 3 |
The split
method returns an array of matching string parts. So basically we are splitting a string with the substring we want to find and checking how many array elements it has returned.
Important Note: The split
method accepts regular expression. While using the above approach, beware of the regular expression metacharacters (characters which have special meaning in regular expression). Consider below given example.
1 2 3 4 5 |
String str = "JavaExamplesJavaCodeJavaProgram"; int count = ( str.split("C++", -1).length ) - 1; System.out.println("Total occurrences: " + count); |
Output
1 |
Total occurrences: 1 |
Surprising result? We do not have “C++” in our string yet our program says it has found it 1 time. That is because the “+” sign has a special meaning in the regular expression and it means “one or more”. We do have “C” one or more times so searching “C++” returns 1. In order to avoid such errors, always use the quote
method of Pattern class whenever you want to do a literal search using split method as given below.
1 2 3 4 5 |
String str = "JavaExamplesJavaCodeJavaProgram"; int count = ( str.split( Pattern.quote("C++" ), -1).length) - 1; System.out.println("Total occurrences: " + count); |
Output
1 |
Total occurrences: 0 |
Please check out string split example for more details.
3) Using the Apache Commons library
If you are using the Apache Commons library, you can use the countMatches
method of the StringUtils class to count occurrences of a substring in the string as given below.
1 2 3 4 5 |
String str = "JavaExamplesJavaCodeJavaProgram"; int count = StringUtils.countMatches(str, "Java"); System.out.println("Total occurrences: " + count); |
Output
1 |
Total occurrences: 3 |
4) Using regular expression
You can also use the regular expression Pattern class to find substring and count it’s occurrences as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
String str = "JavaExamplesJavaCodeJavaProgram"; int count = 0, startIndex = 0; Pattern p = Pattern.compile("Java", Pattern.LITERAL); Matcher m = p.matcher(str); while(m.find(startIndex)){ count++; startIndex = m.start() + 1; } System.out.println("Total occurrences: " + count); |
Output
1 |
Total occurrences: 3 |
This approach is similar to the indexOf
approach except that it uses the find
method of the Matcher class to find a match. The Patter.LITERAL
flag will ignore regular expression metacharacters and treat them as literal.
This example is a part of the Java String tutorial and Java RegEx tutorial.
Please let me know your views in the comments section below.
I do like option #3. There are a lot of useful String utilities in the commons.lang.StringUtils library.
Yes, its must have library for any Java project.
oh, ty very much. It helped me so much in my project. Now I can get all the substrings from my string. .
Glad I could help. Do checkout the quiz section, its a fun way to learn Java.
Don t you also want to account for the case where the prefix of the search string is its suffix? In that case, I don t think any of the suggested answers would work. here is an example. In that case, you would need a more elaborate algorithm, like the Knuth Morris Pratt(KMP) which is coded up in the CLRS book