Stringbuild is a dynamic object that can be directly spelled with a string, while the steps of a String object: Initialize the object and assign a value, and then when you spell the string, create a string that needs to be spelled, and then add it, So that's why stirngbuild is much more efficient than string!
A The String object is immutable. Each time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new space to be allocated for the new object. The overhead associated with creating a new string object can be very expensive in situations where you need to perform repeated modifications to the string.
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 you concatenate many strings together in a loop. StringBuilder run speed heard is a string 200 times times.
By initializing a variable with an overloaded constructor method, you can create a new instance of the StringBuilder class, as illustrated in the following example.
StringBuilder Mystringbuilder = new StringBuilder ("Hello world!");
StringBuilder object setting capacity and length
The StringBuilder object is a dynamic object that allows you to expand the number of characters in the string it encapsulates, specifying a value for the maximum number of characters it can hold.
StringBuilder Mystringbuilder = new StringBuilder ("Hello world!", 25);
In addition, you can use the read/write capacity property to set the maximum length of an object. The following code example uses the capacity property to define the maximum length of an object.
Mystringbuilder.capacity = 25;
Several common methods of this class are listed below:
static void Main (string[] args) { StringBuilder mystringbuilder = new StringBuilder ("Hello world!"); Mystringbuilder.append ("My name is Haoge!"); Add data to the end of the original string. //mystringbuilder.capacity =100; Write maximum capacity; //mystringbuilder.length = 0; Emptying Data //mystringbuilder.remove (0,mystringbuilder.length);//emptying Data Mystringbuilder.insert ("222222"); The 18th character is inserted after the 222222 mystringbuilder.replace ("is", "was"); Replace is with IS. Console.WriteLine (mystringbuilder); int MyInt =45; StringBuilder MyStringBuilder1 = new StringBuilder ("Your Total is"); Mystringbuilder1.appendformat ("{0:c}", MyInt); Console.WriteLine (MyStringBuilder1); Console.readkey ();
Go Stringbulider simple usage of C #