File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes substring() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "substring()" Watch "substring()" New topic
Author

substring()

jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
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

Joined: May 21, 2006
Posts: 425

Am I missing something here? What you've shown seems perfectly fine to me.
Have you read this?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37953
    
  22
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

Joined: Aug 16, 2005
Posts: 14074
    
  16

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18509
    
  40


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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
wood burning stoves
 
subject: substring()
 
Similar Threads
How to display values in an array
asking about substring searching method
Substring
my webcrawler throws: java.lang.OutOfMemoryError: Java heap space
Vector problem