Problem: Write a program in Java to count and output the frequency of a substring in a given string.

Example:

To count the frequency of a substring in a given string, we match the substring with the subset of the given string using the contain() method.

If a match is found, we increment the counter and remove the match from the string. We repeat this process until all the matches are found.

Steps to follow to count the frequency of a substring in a string in Java:

  1. Input the string and substring.
  2. Check using the contain() method if the string contains the given string.
  3. If so, then increment the counter and remove the first letter of a substring from the string using the substring() method.
  4. Repeat steps 2 and 3 until the contain() method gives a positive result.
  5. Output the value of the counter.

The substring(start, end + 1) is a method available in the String class that trims a string from the ‘start’ index to the ‘end’ index.

Whereas the contain(substring) checks the existence of the substring in the given string. If present, it returns the index of its first appearance otherwise it returns -1.

Here is the Java program that implements the above steps to count the frequency of a substring in a string:

Output:

Enter the main String:
TimsdsfTimsfdTim
Enter the match String:
Tim
Count: 3

Enter the main String:
sssss
Enter the match String:
ss
Count: 4

In the above program, when a match is found in the string we remove its first letter using the substring() method so that it doesn’t get match again.

The reason behind removing only the first letter instead of the whole match is that a part of the match could constitute another match like ‘ss’ in ‘sssss’.

Breakdown of the Program:

This is just one way of counting the frequency of a substring in Java. There are lot other methods using which we can efficiently do the same task.

Leave a Reply

eight + nine =