6

I was using substring in a project, earlier I was using endindex position which was not creating the expected result, later I came to know that java substring does endindex-1. I found it not useful. So why Java is doing endindex-1 instead of plain endindex ?

My code is as follows.

String str = "0123456789";
String parameter1 = str.substring(0,4);
String parameter2 = str.substring(5,8);`
3

3 Answers 3

7

It has a number of advantages, not least that s.substring(a,b) has length b-a.

Perhaps even more useful is that

s.substring(0,n)

comes out the same as

s.substring(0,k) + s.substring(k,n)
Sign up to request clarification or add additional context in comments.

Comments

3

Java always uses the begin parameter as inclusive and the end parameter as exclusive to determine a range.

[0:3[ <=> 0, 1, 2
[4:6[ <=> 4, 5

you will find this behaviour several time within the API of java: List, String, ...

it's defined years ago within the java spec. and imho this is awesome and very useful. So with this definition you can make this.

String x = "hello world";
String y = x.substring(0, x.length() - 6); // 6 = number of chars for "world" + one space.
StringBuilder builder = new StringBuilder(y);
builder.append(x.subSequence(5, x.length())); // 5 is index of the space cause java index always starts with 0.
System.out.println(builder.toString());

Otherwise you always have to calculate to get the real last char of a String.

Comments

2

The javadoc explains why, by having it this way

endIndex-beginIndex = length of the substring

The parameters are therefore defined as

beginIndex - the beginning index, inclusive. endIndex - the ending index, exclusive.

A use case would be when you do something like

int index = 3;
int length = 2;
str.substring(index,index+length); 

Its just easier to programatically do things when uses the endIndex in the exclusive way

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.