Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with StringBuffer  RSS feed

 
Håkan Axheim
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hallo!

I have a problem with a Java code that uses the StringBuffer class.
My source code is like this:

public String replaceStr(String veryLongString)
{
StringBuffer buf = new StringBuffer(veryLongString); // veryLongString = 2178
buf.replace(1096,1780,"Test"); // buf = 2180
}

Why is buf 2 characters longer than veryLongString?




 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
buf.replace(1096,1780,"Test"); // buf = 2180

You are replacing 784 characters long string with 4 characters long string "Test" and it still returning you buffer length 2180..
 
Håkan Axheim
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tushar Goel wrote:
buf.replace(1096,1780,"Test"); // buf = 2180

You are replacing 784 characters long string with 4 characters long string "Test" and it still returning you buffer length 2180..


Wrong --> buf.replace(1096,1100,"Test");
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16026
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How are you measuring how many characters are in buf? Are you using the capacity() method or the length() method?

You should be using length(); capacity() only tells you how large the internal buffer of the StringBuffer is, not how many characters it currently holds.

From your code, I would expect that the number of characters in buf after replace() would be veryLongString.length() - (1780 - 1096) + 4 = veryLongString.length() - 680 characters, and not veryLongString.length() + 2 characters.
 
Stephan van Hulst
Saloon Keeper
Posts: 7799
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On a tangent, is there a reason you're using a StringBuffer and not a StringBuilder?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!