Java Data Type How to - Get sub string from a string








Question

We would like to know how to get sub string from a string.

Answer

We can use the substring() method to get a sub-part of a string.

We can takes the start index as the parameter and returns a substring beginning at the start index to the end of string.

We can also takes the start index and the end index as parameters.

It returns the substring beginning at the start index and one less than the end index.

For example,

String s1  = "Hello".substring(1); // s1  has  "ello" 
String s2  = "Hello".substring(1, 4); // s2  has  "ell"
public class MainClass{
/*from   w w  w .  j  av a 2s  .c  o m*/
  public static void main(String[] arg){
    String place = "abcedfghijk";
    String lastWord = place.substring(5);

    System.out.println(lastWord);
  }

}

The code above generates the following result.

Beyond the last character of the substring

public class MainClass{
//from  ww w.java 2 s . c  om
  public static void main(String[] arg){
    String place = "abcedfghijk";
    String segment = place.substring(7, 11);

    System.out.println(segment);
  }

}

The code above generates the following result.