This post will discuss how to find the total number of occurrences of one string in another string in Java. A null or a string input should return 0.

1. Using indexOf() method

The idea is to use the indexOf() method of the String class, which returns the index within this string of the first occurrence of the specified substring, starting at the specified index. It returns -1 if there is no such occurrence.

The trick is to start from the position where the last found substring ends. This is demonstrated below:

Download  Run Code

Output:

3

2. Using split() method

The tricky solution is to use the split() method to split the string around the given substring. This is demonstrated below:

Download  Run Code

Output:

3

3. Using Pattern matching

We can also take the help of regular expressions in Java to count the substring frequency, as shown below:

Download  Run Code

Output:

3

4. Using Apache Commons Lang

Finally, we can leverage the Apache Commons Lang library, which has the countMatches() method included in the StringUtils class for this exact purpose.

Download Code

Output:

3

That’s all about finding the occurrences of a substring in a string in Java.