Wednesday, 18 May 2016

Java program to extract a substring between two substrings in a String

Requirement: Java program to extract a substring between two substrings in a String
Description: I have a String s 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>";
Now from the above String s I want to extract only that part of the String s which is in between  "<table" and "</table>".
Program: The Java program for the above requirement is shown below:
package com.susanto;

public class StringDemo1 {

       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>";
              int startPosition1 = s.indexOf("<table") + "<table".length();
              int endPosition1 = s.indexOf("</table>", startPosition1);
              System.out.println("startPosition1 : " + startPosition1);
              System.out.println("endPosition1 : " + endPosition1);
              String s1 = s.substring(startPosition1 - 6, endPosition1 + 8);

              System.out.println("Thus the new Sub String is : " + s1);
       }

}

Output:
startPosition1 : 35
endPosition1 : 81
Thus the new Sub String is : <table style="MARGIN:39.75pt;><font size="3"></font></table>

Hence, the solution to our requirement.
If you like the posts, please comment, share and like me on Facebook.

Thanks & Regards,
Susanto Paul