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);`
romants
  • 3,660
  • 1
  • 21
  • 33
prsutar
  • 429
  • 2
  • 4
  • 17
  • is this related to regex? – Avinash Raj Dec 05 '14 at 15:58
  • Possible duplicate http://stackoverflow.com/questions/16717740/who-does-substringstartindex-endindex-return-string-from-startindex-start-till? – romants Dec 05 '14 at 16:02
  • Related (or duplicate): [Why is substring() method substring(start index(inclusive), end index (exclusive))](http://stackoverflow.com/questions/26631078/why-is-substring-method-substringstart-indexinclusive-end-index-exclusive) – Pshemo Dec 05 '14 at 16:13

3 Answers3

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)
chiastic-security
  • 20,430
  • 4
  • 39
  • 67
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

abcdef
  • 441
  • 3
  • 13
2

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.

Niels
  • 302
  • 1
  • 2
  • 9