Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java substring endindex-1

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);`
like image 507
prsutar Avatar asked Dec 05 '14 15:12

prsutar


People also ask

What does str substring 1 do in Java?

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.

Does Java substring start at 0 or 1?

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.

How do I find a particular substring in a string in Java?

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.

How does substring () inside string works?

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).


2 Answers

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)
like image 61
chiastic-security Avatar answered Sep 22 '22 10:09

chiastic-security


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

like image 40
abcdef Avatar answered Sep 18 '22 10:09

abcdef