Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append two stringBuilders?

Is there a way to append two string builders? And if so - does it perform better than appending a string to a StringBuilder ?

like image 401
Elad Benda Avatar asked Jun 23 '11 13:06

Elad Benda


People also ask

Can I append StringBuilder to StringBuilder?

StringBuilder has a public StringBuilder append(CharSequence s) method. StringBuilder implements the CharSequence interface, so you can pass a StringBuilder to that method.

What is append StringBuilder in Java?

append(String str) method appends the specified string to this character sequence. The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument.

What is append in StringBuilder append?

StringBuilder. append(boolean a) is an inbuilt method in Java which is used to append the string representation of the boolean argument to a given sequence. Syntax : public StringBuilder append(boolean a) Parameter: This method accepts a single parameter a of boolean type and refers to the Boolean value to be appended.


2 Answers

I know this is three years later, but the .NET 4 StringBuilder behaves differently anyway.

Nevertheless, it does still come back to "what do you want to do?" Are you looking for simply the most performant way of appending two StringBuilders and continuing on with just the latter result? Or are you expecting to continue working with the existing buffered value of the appended StringBuilder?

For the former, and always in .NET 4,

frontStringBuilder.Append(backStringBuilder); 

is best.

For the latter scenario in .NET 2/3.5,

frontStringBuilder.Append(backStringBuilder.ToString(0, backStringBuilder.Length)); 

is best (and won't hurt performance in .NET 4).

like image 199
Mark Hurd Avatar answered Sep 20 '22 20:09

Mark Hurd


Just like that....

StringBuilder sb = new StringBuilder(); StringBuilder sb1 = new StringBuilder(); sb.Append(sb1.ToString()); 
like image 44
Gaurav Agrawal Avatar answered Sep 23 '22 20:09

Gaurav Agrawal