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

The indexOf() method finds the next occurrence of the substring starting from the current index, and a loop increments the count and advances the index past each match, together counting all substring occurrences.

Quick Links to Explore