substring() Extract Part of a String

Here, we use the overloaded methods of substring() to extract the whole or a part of a string.

Following is the signature of overloaded substring() method as defined in String class.

  1. String substring(int indexNum): Returns a string containing all the characters existing from indexNum to the end in the given string.
  2. String substring(int indexNum1, int indexNum2): Returns a string containing all the characters existing from indexNum1 to indexNum2-1 in the given string.
Following program illustrates the above twosubstring() methods.
public class ExtractingString
  public static void main(String args[])
     String s1 = "IndianOcean";

     String s2 = s1;                     // extracting all characters
     System.out.println(s2);             // prints IndianOcean

     String s3 = s1.substring(6);
     System.out.println(s3);             // prints Ocean

     String s4 = s1.substring(2, 8);     // extracting few characters
     System.out.println(s4);             // prints dianOc

		                         // one example to separate all the Web server names

     String names[] = { "",  "",  "",  "" };
     System.out.println("\nFollowing are the Web server names");

     for(int i = 0; i < names.length; i++)
        int a = names[i].indexOf('.');    
        int b = names[i].lastIndexOf('.');
        String str = names[i].substring(a+1, b);
Output screen of

Details of the methods substring() used in the above program.

  1. s1.substring(6) extracts from s1, 6th character onwards to the last. The extracted string is Ocean.
  2. s1.substring(2, 8) extracts from s1, all the characters starting from 2 to 7 (8-1). The extracted string is dianOc
  3. names.length returns the number of elements in the array names.

int a = names[i].indexOf('.');
int b = names[i].lastIndexOf('.');

The integers a and b contains the dot positions of first and last occurrences in each Web server name.

String str = names[i].substring(a+1, b);

Notice, a includes the dot position also in the string. a+1 avoids the dot in the output. Anyhow, b moves one position backwards and itself avoids the dot.

2 thoughts on “substring() Extract Part of a String”

Leave a Comment

Your email address will not be published.