• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

substring()

 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any reason why the ending argument is not zero based in substring() ? It just adds to confusion !!!


String x="0123456789";

s.o.pln(x.substring(5)); output is 56789
s.o.pln(x.substring(5,8)); output is 567
 
Pushkar Choudhary
Rancher
Posts: 425
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Am I missing something here? What you've shown seems perfectly fine to me.
Have you read this?
 
Campbell Ritchie
Sheriff
Posts: 48371
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can work out the length of the substring easily by subtracting the two numbers.

It is probably like that because older functions in C/C++ used that numbering convention, and Gosling kept what he thought was familiar to programmers in 1995.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15205
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The ending number is zero-based, but you have to specify the index one past the last character that you want to be included. So the starting index is inclusive, and the ending index is exclusive. As Campbell says, it's probably that way because of conventions in other programming languages.
 
Henry Wong
author
Marshal
Pie
Posts: 20881
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Agreed. The concept of inclusive start and exclusive end, is used in practically every other system that has substring -- and is intuitive to anyone that has ever used substring in any programming language.


On the other hand, I guess it can get confusing to someone who is just learning his/her first language.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic