substring() Extract Part of a String

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.

substring()

Output screen of ExtractingString.java

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.

Leave a Reply

Your email address will not be published. Required fields are marked *