Possible Duplicate:
why from index is inclusive but end index is exclusive?
substring() method => String substring(int beginIndex, int endIndex)
Description:
Returns a new string that is a substring of this string. The first integer argument specifies the index of the first character. The second integer argument is the index of the last character - 1.
Take a look at the following code:
String anotherPalindrome = "Niagara. O roar again!";
String roar = anotherPalindrome.substring(11, 15);
Output: roar
Now, if the JVM didn't substract int endIndex by one, we could just use substring(11,14) instead, wouldn't that be much more convenient and less error-prone (human side)? Had you not read the description carefully, you might just ended up scratching your head for half an hour (like I did) when you thought that endIndex is just the normal index. What's the reason for the Java language creators to subtract it by one?
It has several advantages:
s.substring(0, s.length())
is always correct. Also:
s.substring(i, j)
The size of resulting string is always j - i. More specifically s.substring(0, j) will always return j characters. Finally this means that if you want to take n characters after index i you simply say:
s.substring(i, i + n)
It's also easier to extract suffix of a string (last n characters):
s.substring(s.length() - n, s.length())
For example extracting file extension:
s.substring(s.indexOf('.') + 1, s.length())
Think of it as numbering the gaps between letters, not the letters themselves:
N i a g a r a . _ O _ r o a r _ a g a i n !
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Clearly, roar is the substring between 11 and 15.
This is the same question as:
"Why do the arrays in Java start at 0 and not at 1".
Indeed, since the arrays start at 0 you usually write:
for(int i = 0; i < ar.length; i++)
similarly if you want a substring starting from start and ending at end you would use something like:
for(int i = start; i < end; i++)
{
//get ar[i]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With