• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String

 
Gaurav Pavan Kumar Jain
Ranch Hand
Posts: 168
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Below code is confusing me please help me to understand

Stringbuffer s="123456789"

s.delete(0,3)
s.replace(1,3,"24")

I cannot understand what will be the output
 
Lucia Short
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the code snippet:

StringBuffer s= new StringBuffer("123456789");
s.delete(0,3);
System.out.println(s);
s.replace(1,3,"24");
System.out.println(s);

The output is:
456789
424789

because in both functions delete(int start, int end) and replace(int start, int end), the start index is 0-based, but the end index is 1-based.
 
Gaurav Pavan Kumar Jain
Ranch Hand
Posts: 168
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your help
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Lucia Short:
...the start index is 0-based, but the end index is 1-based.

That's not the way you should look at it. Look at it this way: Both indices are 0-based, but the begin index is inclusive, and the end index is exclusive.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jesper Young:

That's not the way you should look at it. Look at it this way: Both indices are 0-based, but the begin index is inclusive, and the end index is exclusive.

Yeah, this is the only part of K&B that really made me shake my head when I first read it. What were they thinking when they wrote this "end index is 1-based" explanation? Not only is it more confusing than the "end index exclusive" explanation, but the official API documentation itself uses the "end index exclusive" terminology. (Bert, if you're around, I'd love to hear your thoughts on this. )
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic