Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder: how to get the final String?

Someone told me that it's faster to concatenate strings with StringBuilder. I have changed my code but I do not see any Properties or Methods to get the final build string.

How can I get the string?

like image 832
Mister Dev Avatar asked Oct 22 '08 22:10

Mister Dev


People also ask

How do you get string out of StringBuilder?

To convert a StringBuilder to String value simple invoke the toString() method on it. Instantiate the StringBuilder class. Append data to it using the append() method. Convert the StringBuilder to string using the toString() method.

How do I add to the end of StringBuilder?

lang. StringBuilder. append(char a): This is an inbuilt method in Java which is used to append the string representation of the char argument to the given sequence. The char argument is appended to the contents of this StringBuilder sequence.

What does StringBuilder return?

Returns a string that contains the character sequence in the builder. Note: You can use any String method on a StringBuilder object by first converting the string builder to a string with the toString() method of the StringBuilder class.


2 Answers

You can use .ToString() to get the String from the StringBuilder.

like image 64
Patrick Desjardins Avatar answered Sep 22 '22 15:09

Patrick Desjardins


When you say "it's faster to concatenate String with a String builder", this is only true if you are repeatedly (I repeat - repeatedly) concatenating to the same object.

If you're just concatenating 2 strings and doing something with the result immediately as a string, there's no point to using StringBuilder.

I just stumbled on Jon Skeet's nice write up of this: http://www.yoda.arachsys.com/csharp/stringbuilder.html

If you are using StringBuilder, then to get the resulting string, it's just a matter of calling ToString() (unsurprisingly).

like image 38
Michael Burr Avatar answered Sep 21 '22 15:09

Michael Burr