substring() String Example


Many methods exist in java.lang.String class used for different string manipulations like checking the availability of a character, to extract a part of a string or to convert a data type to string etc. The present method is substring() String.

substring(int) and substring(int, int) extracts part of a string.

substring() method is overloaded 2 times in String class. Both will return a substring from a string. Following are method signatures.

  • public String substring(int beginIndex): Returns a new string containing characteres from beginIndex to the end of the original string.
  • public String substring(int beginIndex, int endIndex): Returns a new string containing characteres from beginIndex to endIndex-1 of the original string. Length of the substring returned will be endIndex-beginIndex.

Following example on substring() String illustrates the usage of the above 2 overloaded methods.

public class StringMethodDemo
{
  public static void main(String args[])
  {
   String str1 = "ABCDEFGHI";                  // index numbering starts from 0	

   String ss1 = str1.substring(3);	       // returns DEFGHI
   String ss2 = str1.substring(3, 7);          // returns DEFG

   System.out.println("ss1:  " + ss1);
   System.out.println("ss2:  " + ss2);
				               // other way to use
   System.out.println("abcdefgh".substring(4));// prints efgh
  }
}


substring() String
Output screenshot on substring() String Example

One practical application on substring() String. To extract Web server names.

public class StringMethodDemo
{
  public static void main(String args[])
  {
   String servers[] = { "www.yahoo.com", "www.gmail.com", "www.rediff.com", "www.lorvent.com" };

   for(int i = 0; i < servers.length; i++)
   {
     int firstDot = servers[i].indexOf('.');    
     int lastDot = servers[i].lastIndexOf('.');
     String serverName = servers[i].substring(firstDot+1, lastDot);

     System.out.println(serverName);
  }
 }


substring() String
Output screenshot on substring() String Example

firstDot+1 is used to eliminate first dot from the substring. Last dot will not come in substring as it becomes lastDot-1.

1 thought on “substring() String Example”

  1. I have a pdf file with various text fields. I need to automate its filling by writing a small java script that basically will extract the substring from a string in a particular text field and write it in a different text field.

    I could email you the pdf file to facilitate the problem understanding

    Thanks

Leave a Comment

Your email address will not be published.