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

Java 8Object Oriented ProgrammingProgramming

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!
raja
Published on 17-Dec-2018 11:17:57
Advertisements