Java String substring() with examples
This method returns a string which is a subset/portion of another string.
There are two variations of this method.
public String substring(int beginIndex)
and
public String substring(int beginIndex, int endIndex)
public String substring(int beginIndex)
This method returns a string from beginIndex to the end of the string.
NB:The index starts at 0.
e.g.
String str = "whitepiano";
System.out.println(str.substring(3));
The above code outputs
tepiano
If the beginIndex is larger than the String size or less than 0(negative),then java.lang.StringIndexOutOfBoundsException will be thrown.
Calling the above code with beginIndex as 0 returns the entire string i.e
String str = "whitepiano";
System.out.println(str.subSstring(0));
Outputs
whitepiano
public String substring(int beginIndex, int endIndex)
This method returns a string formed from beginIndex(inclusive) to endIndex-1(endIndex is exclusive)
It will throw java.lang.StringIndexOutOfBoundsException if beginIndex is negative,endIndex is greater than string length or beginIndex is larger than endIndex.
e.g
String str = "whitepiano";
System.out.println(str.substring(2,6));
The above code will output itep
Some common use cases of String substring method.
1.Suffix and Prefix extraction e.g getting the currency of amount to process from a string containing both currency code and amount e.g USD300.21 -> "USD300.21".substring(3) will return the amount 300.21.This is assuming that currency code will always be 3 characters long.