Tuesday, 17 May 2016

Java Program to count the occurrence of a Sub String inside a String

Requirement:  Java Program to count the occurrence of a Sub String inside a String.

I have a String as shown below:

String s =  "<p><font size=\"3\"></font></p><table style=\"MARGIN:39.75pt;><font size=\"3\"> </font></table><p><font size=\"3\"></font></p><table style=\"MARGIN: 56.75pt; ><font size=\"3\"></font> </table>";

In the above String s we have the Sub String "<table" appearing 2 times. Now my requirement is to count the number of times the Sub String "<table" appearing in the above String s.

Program: The Java program for the above requirement is shown below:

package com.susanto;

public class StringDemo {
       public static void main(String[] args) {
              String s = "<p><font size=\"3\"></font></p><table style=\"MARGIN:39.75pt;><font size=\"3\"></font></table><p><font size=\"3\"></font></p><table style=\"MARGIN:56.75pt;><font size=\"3\"></font> </table>";
              String findTableStr = "<table";
              int lastTableIndex = 0;
              int countTable = 0;
              while (lastTableIndex != -1) {
                     lastTableIndex = s.indexOf(findTableStr, lastTableIndex);
                     if (lastTableIndex != -1) {
                           countTable++;
                           lastTableIndex += findTableStr.length();
                     }
              }
              System.out.println("Number of times <table appearing in the String s : " + countTable);
       }
}
Output: Number of times <table appearing in the String s : 2
Hence, the solution to our requirement.
If you like the posts, please comment, share and like me on Facebook.

Thanks & Regards,

Susanto Paul