Skills of using StringBuilder class to operate string in C and. NET framework

  • 2021-07-24 10:41:54
  • OfStack

But if 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 is no chaining effect of the + operator.


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

    // Use StringBuilder for concatenation in tight loops.
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    for (int i = 0; i < 100; i++)
    {
      sb.AppendLine(i.ToString());
    }
    System.Console.WriteLine(sb.ToString());

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

Output:


0

1
2
3
4
...

Using the StringBuilder class in. NET Framework
String objects are immutable. Each time a method in the System. String class is used, a new string object is created in memory, which requires new space for the new object. The overhead associated with creating a new String object can be significant in situations where repeated modifications to strings are required. If you want to modify a string without creating a new object, you can use the System. Text. StringBuilder class. For example, using the StringBuilder class can improve performance when concatenating many strings at the beginning of 1 in a loop.

Instantiating an StringBuilder object
You can create a new instance of the StringBuilder class by initializing variables with an overloaded constructor method, as illustrated in the following example.


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

Set capacity and length
Although StringBuilder is a dynamic object that allows you to expand 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 of 1. This value is called the capacity of the object and should not be confused with the length of the string that the current StringBuilder holds. For example, you can create a new instance of the StringBuilder class using the string "Hello" of length 5, and you can specify that the maximum capacity of the object is 25. When the StringBuilder is modified, the object does not reallocate space for itself until capacity is reached. When the 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 white spaces.


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

In addition, 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.


MyStringBuilder.Capacity = 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. Setting the Length property to a value less than the length of the string within the current StringBuilder object shortens the string.

Modify the StringBuilder string
The following is a list of methods that can be used to modify the contents of StringBuilder:
1.StringBuilder.Append
Appends information to the end of the current StringBuilder.
2.StringBuilder.AppendFormat
Replaces the format specifier passed in the string with formatted text.
3.StringBuilder.Insert
Inserts a string or object into the specified index of the current StringBuilder object.
4.StringBuilder.Remove
Removes the specified number of characters from the current StringBuilder object.
5.StringBuilder.Replace
Replaces the specified character at the specified index.

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


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

Output:


Hello World! What a beautiful day.

2.AppendFormat
The StringBuilder. AppendFormat method adds text to the end of the StringBuilder object. This method supports composite formatting by calling the IFormattable implementation of the object to be formatted (see Composite Formatting for more information). Therefore, it accepts standard format strings for numbers, date and time, and enumeration values, custom format strings for numbers, date and time values, and format strings defined for custom types. (For formatting information, see Formatting Types in. NET Framework.) You can use this method to customize the format of variables and append these values to the end of StringBuilder. The following example uses the AppendFormat method to place an integer value formatted as a currency value at the end of an StringBuilder object.


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

Output:


Your total is $25.00  

3.Insert
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 1 word into the sixth position of the StringBuilder object.


StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
MyStringBuilder.Insert(6,"Beautiful ");
Console.WriteLine(MyStringBuilder);

Output:


0

1
2
3
4
...

0

Step 4 Remove
You can use the Remove method to remove a specified number of characters from the current StringBuilder object, starting at the specified zero-based index. The following example uses the Remove method to shorten an StringBuilder object.


0

1
2
3
4
...

1

Output:


0

1
2
3
4
...

2

5.Replace
You can use the Replace method to replace a character within an StringBuilder object with another specified character. The following example uses the Replace method to search an StringBuilder object for an exclamation point character (! ) and replace it with the question mark character (? ).


StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
MyStringBuilder.Replace('!', '?');
Console.WriteLine(MyStringBuilder);

Output:


0

1
2
3
4
...

4

Convert an StringBuilder object to an String
You must first convert an StringBuilder object to an String object before you can pass the string represented by an StringBuilder object to a method with an String parameter and display it in the user interface. You can perform this transformation by calling the StringBuilder. ToString method. The following example calls many StringBuilder methods, and then calls the StringBuilder. ToString () method to display the string.


0

1
2
3
4
...

5

Output:


0

1
2
3
4
...

6

Related articles: