In this article, we are going to look at how to use String's substring operation.
Contents
- Get substring using a starting index
- Get substring using start and ending indexes
To get the substring from string using its starting index, we can use String.substring(int beginIndex) inbuilt function of String's class.
It returns the substring starting from position index beginIndex to the end of string.
For example, if the input string is "Hello World" and you want to get substring "World", then we can get it by calling substring(int beginIndex) with input parameter as
6.
public class SubString {
public static void main(String[] args) {
String str = "Hello World";
System.out.println(str.substring(6));
}
}
When you run the above program, you will get the below output.
substring starting from index 6 : World
Explanation : the characters array in the String will look like this H,e,l,l,o, ,W,o,r,l,d.
When we call substring(6), it takes all characters starting from index 6, which is 'W' until the end of string and returns it.
To get the substring between two indexes, we can use String.substring(int beginIndex, int endIndex) or String.subSequence(int beginIndex, int endIndex)inbuilt functions of String's class.
Both returns the substring start.ing from position index beginIndex to the endIndex (exclusive, meaning excludes the endIndex).
For example, if the input string is "Hello World" and you want to get substring "Hello", then we can get it by calling substring(int beginIndex, int endIndex)
with input parameters 0 and 5.
public class SubString {
public static void main(String[] args) {
String str = "Hello World";
System.out.println("substring from 0 and 5 indexes : "+str.substring(0, 5));
System.out.println("substring from 0 and 5 indexes : "+str.subSequence(0, 5));
}
}
When you run the above program, you will get the below output.
substring from 0 and 5 indexes : Hello
substring from 0 and 5 indexes : Hello
Notice that both substring and subSequence produces the same output.
Above example complete source code can be found at Github