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);`
Deleting the first character : Strings in Java start at index 0, i.e., the first character is 0 indexed. If you need to remove the first character, use substring(1). This returns the substring without the initial character, which equals deleting the first character.
The substring begins with the character at the specified index and extends to the end of this string. Endindex of substring starts from 1 and not from 0.
To locate a substring in a string, use the indexOf() method. Let's say the following is our string. String str = "testdemo"; Find a substring 'demo' in a string and get the index.
The substring begins with the character at the specified index and extends to the end of this string. substring(int beginIndex, int endIndex) : 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).
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With