Way2Java

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.

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
  }
}



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);
  }
 }



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.