Write a program in java to count and output the frequency of a substring in a given string.

Example:

For this, we will use the inbuilt String class contain() method.

contain() returns the index of first appearance of the (i.e substring) in the string if present otherwise it returns -1.

Using this we will check whether the given substring is present in the main string or not, if yes then will increment the count variable and will update the main string by removing the already counted substring for another round of check.

Note: substring(start, end + 1) is a String class method, which trims and return the string from ‘start’ index to ‘end’ index.

Frequency of a Substring in a String in Java

Output

If you have any doubt or suggestion then comment below.

Leave a Reply

Close Menu