First, the two classes have different working principles: the string class is a traditional string modification method. When you add a string to another string, the system first writes the two strings to the memory, delete the original string object, create a string object, and read the data in the memory to the object.
The StringBuilder class in the System. Text namespace is different. The Append method provided by the StringBuilder class can be used to modify strings in the existing object. This saves a lot of time than the string method (when a string is connected together in a loop, the StringBuilder class can improve performance)
Excerpt the StringBuilder class description:
① Set the capacity and length
StringBuilder MyStringBuilder = new StringBuilder ("Hello World ");
The StringBuilder object is a dynamic object that allows you to expand the number of characters in its encapsulated string, but you can specify a value for its maximum number of characters, that is, the capacity of the object, when you modify StringBuilder to reach the maximum capacity, it will automatically allocate new space and double the capacity.
StringBuilder MyStringBuilder = new StringBuilder ("Hello, World! ", 25 );
You can also use MyStringBuilder. Capatity = 25, that is, the Capacity attribute to set the maximum length of an object.
② Use of the StringBuilder Method
Append the string to the end of the current StringBuilder.
StringBuilder sb = new StringBuilder ("Hello, World! ");
Sb. Append ("What a beautiful day .");
Console. WriteLine (sb );
Output: Hello, World! What a beautiful day.
AppendFormat replaces the format specifier passed in the string with formatted text.
Int MyInt = 25;
StringBuilder sb = new StringBuilder ("Your total is ");
Sb. AppendFormat ("{0: C}", MyInt );
Console. WriteLine (sb );
Output: Your total is ¥25.00.
Insert inserts a string into the index specified by the current StringBuilder object.
For example, insert a word to the sixth position of StringBuilder.
StringBuilder sb = new StringBuilder ("Hello, World! "); Sb. Insert (6," beautiful ");
Output: Hello, beautifulWorld!
Remove removes a specified number of characters from the current StringBuilder object.
Deletes the specified number of characters from the index starting from scratch.
StringBuilder sb = new StringBuilder ("Hello, World! "); Sb. Remove (4, 3 );
Output: Hellorld!
Replace replaces the characters at the specified index.
StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ");
MyStringBuilder. Replace (!, );
Console. WriteLine (MyStringBuilder );