BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

The StringBuilder Class

Creating strings with the use of multiple concatenation operations can lead to low performance and wasteful memory usage. The StringBuilder class allows strings to be created and updated without the problems caused by the immutability of the String class.

Insert

In addition to concatenating strings, the StringBuilder class allows a string to be inserted at any position within its contents, using the Insert method. This method accepts two arguments. The first specified the position at which characters should be inserted. The second parameter can be any value or object. The string representation of the second parameter is added at the desired location.

StringBuilder sb = new StringBuilder();
sb.Append("The winner was .");
sb.Insert(15, "Bob");
Console.WriteLine(sb);  // Outputs "The winner was Bob."

Replace

The Replace method allows a simple "search and replace" operation to be carried out upon the contents of a StringBuilder. You can search for a single character or an entire string to be replaced with an alternative. The following sample uses strings.

StringBuilder sb = new StringBuilder();
sb.Append("The winner was Bob.");
sb.Replace("Bob", "Jan");
Console.WriteLine(sb);  // Outputs "The winner was Jan."

NB: The Replace method can also be used to replace characters within a substring of the StringBuilder's contents by providing a starting index and length for the substring.

Remove

The last member for changing a StringBuilder's contents is the Remove method. This method removes a substring that is defined using a start index and length.

StringBuilder sb = new StringBuilder();
sb.Append("The winner was NOT Bob.");
sb.Remove(14, 4);
Console.WriteLine(sb);  // Outputs "The winner was Bob."

Chaining Methods

One interesting aspect of the six methods described above is that each returns a reference to the StringBuilder. This provides the possibility of chaining the methods together, which can lead to code that is easier to read and maintain. When chaining methods together, they are executed in the order in which they appear. For example:

string player = "Bob";
int points = 1234;
TimeSpan duration = new TimeSpan(1, 30, 0);

StringBuilder sb = new StringBuilder();
sb.Append("The winner was ")
  .Append(player)
  .AppendLine(".")
  .AppendFormat("This player scored {0:#,#} points in {1}.", points, duration)
  .Replace("Bob", "Jan");

Console.WriteLine(sb);

/* OUTPUT

The winner was Jan.
This player scored 1,234 goals in 01:30:00.

*/
25 October 2009