Index Value of Java Substring
When we use a substring to extract a part of the String, then we we provide the starting index value. We may use both the starting and ending value of index also.The index value of a String stats from 0 and goes till one less then the length of the String. The below diagram clears this.
Suppose that we have a string called:-
String str = "index value of substring";
In memory the string is stored as:-
So the string is stored starting at an index value of 0 to one less then the string length. Now there are two substring() operation possible on this. They are explained below:-
substring(startIndex)
When we want to retrive a substring from the original string, such that it starts from some index vale of the string and goes till the end of the String, then we use this method.
Using the above example, suppose we say:-
String subStr1 = str.substring(6);
Then the output is:-
value of substring
The below diagram explains this:-
So the method substring(startIndex) includes the starting index value while extracting the substring.
substring(startIndex, endIndex)
This method is used to extract a part of the string starting from the startIndex value and ending at the endIndex value.
Using the same example, suppose we say:-
String subStr1 = str.substring(6, 18);
Then the output is:-
value of sub
The below image explains this:-
So the method substring(startIndex, endIndex) includes the starting Index value but excludes the ending Index value.
Related Articles
Substring Index Out of Range Exception Convert int to String in Java
Convert int to String using Wrapper in Java
Java String Length Program
Reverse a String in Java
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.