Substring in java
Substring means part of a string. Many times in an application, we get a long string and we need to extract some portion from it.
java.lang.String
class provides substring()
method for this purpose.
substring()
method as explained below.1. substring(int beginIndex)
Accepts an integer as argument and returns the string starting from this index till the end of string. Example,
"codippa.com".substring(8)
will return “com”.Remember that string indexing starts at 0.
That is, first character will be at index 0, second at 1 and so on. Thus, the character at 8th index in above example will be ‘c’.
2. substring(int beginIndex, int endIndex)
This method is used when you want a portion of string between two indexes.
Returned string will have index between beginIndex and (endIndex – 1). This means that the character at endIndex will not be included in the result.
Example,
"codippa.com".substring(0, 7)
will return “codippa”, which is the string between indexes 0 and 6.
Each of these methods should be called on a string and returns a new string which is the substring as per the provided index(es).
Original string remains unchanged.
Following is an example program that demonstrates the use of single argument
substring
method.
public class SubstringDemo { public static void main(String[] args) { String str = "codippa.com"; // get string after 8th character String subStr = str.substring(8); System.out.println(subStr); } }
It will print
com
Substring example: Second method
Below program shows an example of how to get substring between two index positions.
public class SubstringDemo { public static void main(String[] args) { String str = "Learning substring"; // get string between 5th and 11th character String subStr = str.substring(4, 12); System.out.println(subStr); } }
Above program will output
ning sub
substring()
is a method of string manipulation in java.
But remember that the original string does not change by calling this method because java.lang.String
class is immutable.
Learn how to create your own immutable class here.
If you liked this post, then hit the clap button below.