Why substring of substring method (start index (inclusive), end index (exclusive))

What is the reason why a substring has an initial parameter as an index, and the second parameter is 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 need to do"ABCDE".substring(1,3);

Why is this so?

EDIT: What are the benefits of an exclusive end index?

+4
source share
4 answers

The question "Why" can be considered philosophical or academic, and provoke answers along the lines of "This is as it is."

However, from a more general, abstract point of view, this is the right question when considering alternatives: you can imagine two forms of this method:

String substringByIndices(int startIndex, int endIndex);

and

String substringByLength(int startIndex, int length);

, : .

, , . :

int startIndex = ...;
int endIndex = ...;
String s = string.substringByLength(startIndex, endIndex-startIndex);

int startIndex = ...;
int length = ...;
String s = string.substringByIndices(startIndex, startIndex+length);

, , , +1 -1 , .

, : , +1 -1:

int startIndex = 12;
int length = 34;
String s = string.substringByIndices(startIndex, startIndex+length);

// One would expect this to yield "true". If the end index
// was inclusive, this would not be the case...
System.out.println(s.length() == length); 

- , for -loops,

for (int i=startIndex; i<endIndex; i++) { ... }

, - . , , .


, , , , :

API.

, List subList (int, int):

List<E> subList(int fromIndex, int toIndex)

fromIndex, inclusive toIndex, .

. API-, , , .

+8

.

, , , , :

"ABCDEFGH".substring(start, start + length);

.

+4

" ", " ".

, , .

:

int start; // inclusive
int end; // exclusive
char[] string;

, :

char[] substring = new char[end - start];
for (int i = start; i < end; i++)
    substring[i - start] = string[i];

, / 1 - - , . :

for (int i = start, j = 0; i < end; i++)
    substring[j++] = string[i];

" ", , C , Java - C.

+1

The rule of thumb when writing code is to accept the maximum amount or input from the consumer. It’s easier to get the desired result.

Source code is the answer. And both of them are starting and ending indices.

   public String substring(int beginIndex, int endIndex) {
1942        if (beginIndex < 0) {
1943            throw new StringIndexOutOfBoundsException(beginIndex);
1944        }
1945        if (endIndex > count) {
1946            throw new StringIndexOutOfBoundsException(endIndex);
1947        }
1948        if (beginIndex > endIndex) {
1949            throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1950        }
1951        return ((beginIndex == 0) && (endIndex == count)) ? this :
1952            new String(offset + beginIndex, endIndex - beginIndex, value);
1953    }

In simple words, just mention where and where you want to tweak it.

0
source

All Articles