SoFunction
Updated on 2025-03-07

Tips for using StringBuilder class to manipulate strings in C# and .NET frameworks

But if the performance is important, you should always use the StringBuilder class to concatenate strings. The following code uses the Append method of the StringBuilder class to concatenate strings, so there will be no linking effect of the + operator.

class StringBuilderTest
{
  static void Main()
  {
    string text = null;

    // Use StringBuilder for concatenation in tight loops.
     sb = new ();
    for (int i = 0; i < 100; i++)
    {
      (());
    }
    (());

    // Keep the console window open in debug mode.
    ("Press any key to exit.");
    ();
  }
}

Output:

0

1
2
3
4
...

Using the StringBuilder class in .NET Framework
A String object is immutable. Every time a method in the class is used, a new string object is created in memory, which requires allocating new space for the new object. In the event that repeated modifications are required to perform a string, the system overhead associated with creating a new String object can be very high. If you want to modify a string without creating a new object, you can use the class. For example, using the StringBuilder class can improve performance when concatenating many strings together in a loop.

Instantiate the StringBuilder object
A new instance of the StringBuilder class can be created by initializing the variable with an overloaded constructor method, as explained in the following example.

StringBuilder MyStringBuilder = new StringBuilder("Hello World!");

Set capacity and length
Although StringBuilder is a dynamic object that allows for augmentation of the number of characters in the string it encapsulates, you can specify the maximum number of characters that the object can hold with a value. This value is called the capacity of the object, and do not confuse it with the length of the string contained in the current StringBuilder. For example, you can use the string "Hello" of length 5 to create a new instance of the StringBuilder class, and you can specify that the maximum capacity of the object is 25. When modifying StringBuilder, the object does not reassign space to itself until the capacity is reached. When capacity is reached, new space will be automatically allocated and the capacity will be doubled. You can use one of the overloaded constructors to specify the capacity of the StringBuilder class. The following example specifies that the MyStringBuilder object can be expanded to a maximum of 25 blanks.

StringBuilder MyStringBuilder = new StringBuilder("Hello World!", 25); 

Additionally, you can use the Read/Write Capacity property to set the maximum length of the object. The following example uses the Capacity property to define the maximum length of an object.

 = 25;

The EnsureCapacity method can be used to check the capacity of the current StringBuilder. If the capacity is greater than the passed value, no changes are made; however, if the capacity is less than the passed value, the current capacity is changed to match the passed value.
You can also view or set the Length property. If the Length property is set to a value greater than the Capacity property, the Capacity property is automatically changed to the same value as the Length property. If the Length property is set to a value smaller than the length of the string in the current StringBuilder object, the string is shortened.

Modify StringBuilder string
The following lists the methods that can be used to modify the content of StringBuilder:

Append information to the end of the current StringBuilder.

Replace the format specifier passed in the string with formatted text.

Insert a string or object at the specified index of the current StringBuilder object.

Removes the specified number of characters from the current StringBuilder object.

Replaces the specified character at the specified index.


The Append method can be used to add a string representation of a text or object to the end of a string represented by the current StringBuilder object. The following example initializes a StringBuilder object to "Hello World" and then appends some text to the end of the object. Space will be automatically allocated as needed.

StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
(" What a beautiful day.");
(MyStringBuilder);

Output:

Hello World! What a beautiful day.


Method adds text to the end of the StringBuilder object. This method supports composite formatting functionality by calling the IFormattable implementation of the object to be formatted (see Composite Format Settings for more information). Therefore, it accepts a standard format string for numbers, dates and times and enumeration values, a custom format string for dates and time values, and a format string defined for custom types. (Format types in the .NET Framework for information about formatting.) You can use this method to customize the formatting of variables and append these values ​​to the back of the StringBuilder. The following example uses the AppendFormat method to place an integer value set to currency value format at the end of the StringBuilder object.

int MyInt = 25; 
StringBuilder MyStringBuilder = new StringBuilder("Your total is ");
("{0:C} ", MyInt);
(MyStringBuilder);

Output:

Your total is $25.00  


The Insert method adds a string or object to the specified location in the current StringBuilder object. The following example uses this method to insert a word into the sixth position of the StringBuilder object.

StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
(6,"Beautiful ");
(MyStringBuilder);

Output:

Hello Beautiful World!

4. Remove
The Remove method can be used to remove a specified number of characters from the current StringBuilder object, and the removal process starts at the specified zero-starting index. The following example uses the Remove method to shorten the StringBuilder object.

StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
(5,7);
(MyStringBuilder);

Output:

Hello


Use the Replace method to replace characters inside the StringBuilder object with another specified character. The following example uses the Replace method to search for all instances of the exclamation mark character (!) in a StringBuilder object and replaces it with a question mark character (?).

StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
('!', '?');
(MyStringBuilder);

Output:

Hello World?

Convert StringBuilder object to String
The StringBuilder object must be converted to a String object before the string represented by the StringBuilder object can be passed to a method with a String parameter and displayed in the user interface. This conversion can be performed by calling the method. The following example calls many StringBuilder methods, and then calls the () method to display the string.

using System;
using ;

public class Example
{
  public static void Main()
  {
   StringBuilder sb = new StringBuilder();
   bool flag = true;
   string[] spellings = { "recieve", "receeve", "receive" };
   ("Which of the following spellings is {0}:", flag);
   ();
   for (int ctr = 0; ctr <= (0); ctr++) {
     ("  {0}. {1}", ctr, spellings[ctr]);
     ();
   }
   ();
   (());
  }
}

Output:

Which of the following spellings is True:
0. recieve
1. receeve
2. receive