Count how many times the substring appears in the larger String in Java


Let’s say we have the following string.

String str = "Learning never ends! Learning never stops!";

In the above string, we need to find out how many times the substring “Learning” appears.

For this, loop until the index is not equal to 1 and calculate.

while ((index = str.indexOf(subString, index)) != -1) {
subStrCount++;
index = index + subString.length();
}

The following is an example.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "Learning never ends! Learning never stops!";
      System.out.println("String: "+str);
      int subStrCount = 0;
      String subString = "Learning";
      int index = 0;
      while ((index = str.indexOf(subString, index)) != -1) {
         subStrCount++;
         index = index + subString.length();
      }
      System.out.println("Substring "+subString+" found "+subStrCount+" times!");
   }
}

Output

String: Learning never ends! Learning never stops!
Substring Learning found 2 times!

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 27-Jun-2020

253 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements