StringBuilder: Manipulating C# Strings More Efficiently

By John Paul Mueller, Bill Sempf, Chuck Sphar

Building longer C# strings out of a bunch of shorter strings can cost you an arm and its elbow. Because a string, after it’s created, can’t be changed; it’s immutable. This example doesn’t tack “ly” onto s1:

string s1 = “rapid”;

string s2 = s1 + “ly”; // s2 = rapidly.

It creates a new string composed of the combination. (s1 is unchanged.) Other operations that appear to modify a string, such as Substring() and Replace(), do the same.

The result is that each operation on a string produces yet another string. Suppose you need to concatenate 1,000 strings into one huge one. You’re going to create a new string for each concatenation:

string[] listOfNames = ... // 1000 pet names

string s = string.Empty;

for(int i = 0; i < 1000; i++)

{

s += listOfNames[i];

}

To avoid such costs when you’re doing lots of modifications to strings, use the companion class StringBuilder. Be sure to add this line at the top of your file:

using System.Text; // Tells the compiler where to find StringBuilder.

Unlike String manipulations, the manipulations you do on a StringBuilder directly change the underlying string. Here’s an example:

StringBuilder builder = new StringBuilder(“012”);

builder.Append(“34”);

builder.Append(“56”);

string result = builder.ToString(); // result = 0123456

Create a StringBuilder instance initialized with an existing string, as just shown. Or create an empty StringBuilder with no initial value:

StringBuilder builder = new StringBuilder(); // Defaults to 16 characters

You can also create the StringBuilder with the capacity you expect it to need, which reduces the overhead of increasing the builder’s capacity frequently:

StringBuilder builder = new StringBuilder(256); // 256 characters.

Use the Append() method to add text to the end of the current contents. Use ToString() to retrieve the string inside the StringBuilder when you finish your modifications. Here’s the StringBuilder version of the loop just shown, with retrieval of the final concatenated string in boldface:

StringBuilder sb = new StringBuilder(20000); // Allocate a bunch.

for(int i = 0; i < 1000; i++)

{

sb.Append(listOfNames[i]); // Same list of names as earlier

}

string result = sb.ToString(); // Retrieve the results.

StringBuilder has a number of other useful string manipulation methods, including Insert(), Remove(), and Replace(). It lacks many of string’s methods, though, such as Substring(), CopyTo(), and IndexOf().

Suppose that you want to uppercase just the first character of a string. With StringBuilder, it’s much cleaner looking.

StringBuilder sb = new StringBuilder(“jones”);

sb[0] = char.ToUpper(sb[0]);

string fixedString = sb.ToString();

This puts the lowercase string "jones" into a StringBuilder, accesses the first char in the StringBuilder’s underlying string directly with sb[0], uses the char. ToUpper() method to uppercase the character, and reassigns the uppercased character to sb[0]. Finally, it extracts the improved string "Jones" from the StringBuilder.

There are several handy methods you can add to the String class. You can convert between strings, arrays of char, and arrays of byte. Those are operations you may need to do frequently.