Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Very basic String question (substring method)

 
Rajeshwari Godbole
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In the Seirra and Bates book, page 387 has the following line:

"String methods use zero based indexes, except for the second argument of substring()."

This is confusing me since the method
public String substring(int beginIndex, int endIndex)
uses zero based index to calculate both beginIndex and endIndex (the only thing is that the endIndex is not included in the result)

Is this a typo or am I not understanding this correctly?

Thanks!
 
Ken Januski
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's correct. If you have a string "abcd", substring(0,2) will give you "ab". That's because the first argument is 0 based, so you get "a",a nd the second is not 0 based, so you get "b". Absolutely inconsistent but correct.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure that is the best way to explain it (well, I am sure that it isn't the best way to explain it but I like Kathy and Bert too much to say so). I think it is clearer to state that the second parameter is a zero-based index but it is exclusive not inclusive.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic