Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

substring()

 
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
 
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?
 
Marshal
Posts: 69756
277
  • 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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • 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.
 
author
Posts: 23878
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux 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
 
    Bookmark Topic Watch Topic
  • New Topic