Substring in java

Substring is a method in the String class that allows to get a subset of a String.

Substring in java methods

There are two methods offered by the String class that return a substring :

public String substring(int startIndex)

this method returns a new string that starts from startIndex inclusive and finishes at the original string’s last index inclusive also (the last index of the original string is at the index originalString.length() -1 )

substring in java example 1

The substring example below displays the substring of the string « abderrahmen » beginning from the index 4 inclusive and finishing at the last index of that string (10 = 11-1)


public class substring {

  public static void main(String[] args){
    String myString = "abderrahmen";
    String substring = myString.substring(4);
    System.out.println(substring);

  }
}

The output of the codeabove is the following :

rrahmen

public String substring(int startIndex, int endIndex)

This method returns a new string beginning from a starting index and finishing at a final index. (the caracter at the final index is excluded from the resulting string )

Substring in java example 2

The substring example below displays the substring of the string « abderrahmen » beginning from the index zero and finishing at the index three (the caracter at the index 3 is excluded).
public class substring {

  public static void main(String[] args){
    String myString = "abderrahmen";
    String substring = myString.substring(0, 3);
    System.out.println(substring);

  }
}

The displayed string is the following :

abd

This core JAVA tutorial which deals with the substring method in java arrives at its end.

To check the other JAVA tutorials, please check our core java tutorial.

Please, don’t forget to follow us on Facebook to get our next JAVA core tutorial.


Post a Comment

Previous Post Next Post