DEV Community

Cover image for Be Careful with String’s Substring Method in Java

Be Careful with String’s Substring Method in Java

Jeremy Grifski on March 01, 2019

Every once in awhile, I’ll come across a well-established library in a programming language that has its quirks. As an instructor, I have to make s...
Collapse
 
maiph profile image
Ricardo Pinheiro

I find it completely normal. Imagine the following: you want to get 3 characters counting from index 5. That means you want from 5 to 5+3=8.
Also, in many others languages you either specify the length of the substring of follow the rule explained. Other than that, you usually do for loops as follow
for (int i=0; i<3; i++), and you already know that i will never be 3.

Collapse
 
renegadecoder94 profile image
Jeremy Grifski • Edited

I totally agree! Both of your examples make perfect sense for people who have coded for a bit. After all, we've all agreed that indices start from 0 (perpetuated by Dijkstra), but that's not intuitive for new folks either.

EDIT: I should clarify that we don't all agree on indexing from 0, but I'd argue that all of the most currently dominant languages index from 0.

Collapse
 
elmuerte profile image
Michiel Hendriks • Edited

We have not agreed to that at all. As in Dijkstra note you linked, ALGOL and Pascal indices start at 1. This is also the case with XSLT/XPath/XQuery.

I don't understand why you are trying to blame index-0 on Dijkstra. His note was written in 1982, years after languages like C were defined. Dijkstra did not set the rule on where to start. Just because he voiced his reasoned opinion on a subject does not give him the blame for what others did.

Besides, the natural world also starts at 0. When you are born you are in your first year, which is from 0 to 1. This confusing problem is everywhere, not just in programming languages.

“Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration.” - Stan Kelly-Bootle

Thread Thread
 
renegadecoder94 profile image
Jeremy Grifski

Again, I agree all the way that this problem is confusing! The entire point of this article is that certain conventions are not always intuitive. That doesn't mean they're bad. It just means there should be a good reason for them.

Also, I'm not saying that Dijkstra is the reason for indexing from 0, but he's clearly made the strongest case for it. There's been less time between the first programming language and what Dijkstra said (24 years) than what he said and today (37 years). He's had an incredible influence on the field in the last 40 years.