#70 – The StringBuilder Class

For more efficient string manipulation, you can use the StringBuilder class, which has methods that allow you to modify its internal character data without allocating a new string for each operation.

A StringBuilder instance wraps a single Unicode string and allows you to modify that string in different ways.

StringBuilder can be found in the System.Text namespace.

Constructing a StringBuilder:

 StringBuilder sb1 = new StringBuilder();    // Empty string
 StringBuilder sb2 = new StringBuilder("Sean");

Modifying internal string:

 sb2.Append(" was here");
 sb2.AppendFormat(" on {0:d}", DateTime.Today);
 sb2.Replace("Sean", "Kilroy");
 sb2.Insert(0, "Mr. ");          // Insert at start of string

Other things that you can do with a StringBuilder object:

 char third = sb2[2];            // 3rd character
 string s = sb2.ToString();      // Convert to string
 int len = sb2.Length;           // # chars

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: