What is the reason why substring has the starting parameter as an index and the 2nd parameter as the length from the beginning?
In other words
1 2 3 | 4 5 <=== Length from beginning
A B C D E
0 | 1 2 3 4 <=== Index
If i want substring() to return BC
i have to do "ABCDE".substring(1,3);
Why is this the case?
EDIT: What are the benefits of making the end index exclusive?
Java String class provides the built-in substring() method that extract a substring from the given string by using the index values passed as an argument. In case of substring() method startIndex is inclusive and endIndex is exclusive.
The substring(int beginIndex, int endIndex) method of the String class. It returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
The substring() method returns a substring of the given string. This is a built-in method of string class that can be called by a string, it returns the substring based on the index values passed to this method. For example: “Beginnersbook”. substring(9) would return “book” as a substring.
The Java String class substring() method returns a part of the string. We pass beginIndex and endIndex number position in the Java substring method where beginIndex is inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0, whereas the endIndex starts from 1.
It's not so much the "length from the start" but "end index exclusive".
The reason is obvious if you look at how those two numbers work with code to create a substring by copying characters from one array to another.
Given:
int start; // inclusive
int end; // exclusive
char[] string;
Now look how easy it is to use those numbers when copying elements of an array:
char[] substring = new char[end - start];
for (int i = start; i < end; i++)
substring[i - start] = string[i];
Notice how there is no adjusting by adding/subtracting 1 - the numbers are just what you need for the loop. The loop could actually be coded without the subtraction too:
for (int i = start, j = 0; i < end; i++)
substring[j++] = string[i];
Choosing those numbers is "machine friendly", which was the way when the C language was designed, and Java is based on C.
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