Find and count occurrences of substring in string in java

Find and count occurences of substring in String in Java

In this post, we will see how to find and count occurrences of substring in string in java.

Using the indexOf() method

The indexOf() method in java is a specialized function to find the index of the first occurrence of a substring in a string. This method has 4 overloads.

We will use the second overload as we have to check the entire string. The fromIndex parameter is used to specify the starting index from where to start the search. This method returns an integer value indicating the position of the occurrence. If it returns -1, then it means that there exists no occurrence in the given string.

Output:

Total occurrences of a substring in the given string: 3
Indices of substring are: [2, 5, 20]

Using regular expression

The regular expression uses a specific syntax or pattern for matching text. We can use a regular expression to match the pattern of our substring and find its occurrences in the given string. In Java, we use the Pattern and Matcher class of regular expression to find the pattern and then match it. It is one of the simplest ways to find the number of occurrences of a substring in a string.

Output:

Total occurrences of a substring in the given string: 3
Indices of substring are: [2, 5, 20]

We have found the occurrences of the substring in the given string using the find() method of the Matcher class. After finding the occurrences, we have counted them by incrementing the count variable.

Using split() method

The split() method in java is used to split a string based on some substring. We will simply use this method with a little logic to find the number of occurrences of a substring in a string. We know that if there exists one pattern of a substring in the given string, then the method will divide the given string into two parts. Using this logic, we will find the length of the array of strings produced as a result of the split() method and subtract 1 from it to find the number of occurrences.

Output:

Total occurrences of a substring in the given string: 3

Using the countMatches() method from Apache Commons library

The StringUtils class of Apache Commons library contains the countMatches() method that can be used to find all occurrences of a substring in a string.
Here is the dependency which you need to add for Apache common lang3 in pom.xml.

Output:

Total occurrences of a substring in the given string: 3

That’s all about how to find and count occurrences of substring in string in java.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.