Substring in Java
There are two variants of the substring() method. This article depicts all of them, as follows :
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
1. String substring(): This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. And index of substring starts from 1 and not from 0.
Syntax : public String substring(int begIndex) Parameters : begIndex : the begin index, inclusive. Return Value : The specified substring.
The extracted substring is : geeksforgeeks
2. String substring(begIndex, endIndex): This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1 if the second argument is given.
Syntax : public String substring(int begIndex, int endIndex) Parameters : beginIndex : the begin index, inclusive. endIndex : the end index, exclusive. Return Value : The specified substring.
The extracted substring is : geeks
Possible application: The substring extraction finds its use in many applications including prefix and suffix extraction. For example to extract a Lastname from the name or extract only denomination from a string containing both amount and currency symbol. The latter one is explained below.
The original string is : Rs 1000 The extracted substring is : 1000
This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.