Java substring endindex-1
Solution 1
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)
Solution 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
Solution 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.
prsutar
Hello, I am a Java/J2EE developer. Technologies I have worked in are J2EE JSP, Servlets, Struts2, Hibernate and Spring.
Updated on August 17, 2022Comments
-
prsutar over 1 year
I was using
substring
in a project, earlier I was usingendindex
position which was not creating the expected result, later I came to know that javasubstring
doesendindex-1
. I found it not useful. So why Java is doingendindex-1
instead of plainendindex
?My code is as follows.
String str = "0123456789"; String parameter1 = str.substring(0,4); String parameter2 = str.substring(5,8);`