• Post Reply Bookmark Topic Watch Topic
  • New Topic

StringBuilder and String  RSS feed

 
Cory Max
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand the difference between the two but I have always used Strings in my code instead of StringBuilders. I am wondering how to set a stringbuilder object = a new string, not to append, not to insert, but to set it to a new string without the overhead of creating another object. for example, with strings I would have done:

String s = "";
for (int i = 0 ; i < 10 ; i ++) {
s = "" + i;
System.out.println(s);
}

Append, appends the string, insert, inserts at a specified index. How do I clear the contents of my stringbuilder and set it equal to a new value?

Thanks folks,

Yeuker
 
Mark Dexter
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since strings are immutable, you are creating a new String object with each iteration. So the StringBuilder will execute faster, since you are only creating one new object at the start of the loop instead a new object with each iteration. If you have "Thinking in Java", see page 506. Hope this helps. Mark Dexter
 
Cory Max
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand what the differences are. I want to know how to clear the contents of the stringbuffer, then insert a new string.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Will the replace method do what you want ?
 
Cory Max
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup. Just what I needed. Just didnt look through the api as far as I should have:

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!