Count Substring Occurrences
This program counts occurrences of substring in string.
Problem Statement
Write a Java program to count occurrences of "ab" in "abababc".
Source Code
| 1 | public class SubstringFrequency { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Substring Frequency"); |
| 4 | String str="abababc", sub="ab"; |
| 5 | int count=0, index=0; |
| 6 | while((index=str.indexOf(sub,index))!=-1){ |
| 7 | count++; index+=sub.length(); |
| 8 | } |
| 9 | System.out.println("Occurrences of '"+sub+"' = "+count); |
| 10 | } |
| 11 | } |
Program Output
Eduinq Substring Frequency Occurrences of 'ab' = 3
Explanation
indexOf() finds substring starting at index. - Loop increments count and moves index forward. - Together counts substring occurrences. Conclusion: Shows how to count substring frequency in string.