Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is substring() method substring(start index(inclusive), end index (exclusive)) [closed]

Tags:

java

string

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?

like image 999
shinjw Avatar asked Oct 29 '14 13:10

shinjw


People also ask

Is substring inclusive or 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.

How does substring () method works?

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.

What is the purpose of the substring () method and how do you use it?

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.

Is substring in Java inclusive exclusive?

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.


1 Answers

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.

like image 103
Bohemian Avatar answered Oct 19 '22 10:10

Bohemian