The usage of StringBuilder in C # And the difference between StringBuilder and String

Source: Internet
Author: User

The String class is unchangeable. Each time you perform the character operation, a New String object is created.

The StringBuilder class solves the problem of creating a large number of objects during repeated modification of strings. After a StringBuilder is initialized, it automatically applies for a default StringBuilder Capacity (the default value is 16), which is controlled by Capacity. in addition, the Capacity size can be controlled as needed, or the Length of StringBuilder can be obtained or set through Length.

Example: Use the String class to write

Copy codeThe Code is As follows: String begin_query = "select UPPER (MachineName) As MachineName," + "LOWER (MachineOwner) As MachineOwner, Status," + "StartTime from NET_STRESS WHERE ";

String end_query = "AND StartTime> '" + startTime + "' AND StartTime <'" + endTime + "'";

String query = begin_query + GetWhereClause ("PASSED") + end_query;

Use the StringBuilder class to write:

Copy codeThe Code is as follows: StringBuilder begin_query = new StringBuilder ();

Begin_query.Append ("select UPPER (MachineName) As MachineName ");

Begin_query.Append ("LOWER (MachineOwner) As MachineOwner, Status ,");

Begin_query.Append ("StartTime from NET_STRESS WHERE ");

StringBuilder end_query = new StringBuilder ();

End_query.Append ("AND StartTime> '");

End_query.Append (startTime );

End_query.Append ("'AND StartTime <'");

End_query.Append (endTime );

End_query.Append ("'");

String query = begin_query.Append (GetWhereClause ("PASSED"). Append (end_query). ToString ();

By initializing variables using an overloaded constructor method, you can create a new instance of the StringBuilder class, as described in the following example.

Copy codeThe Code is as follows: StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ");

Set capacity and length
Although the StringBuilder object is a dynamic object that allows you to expand the number of characters in its encapsulated string, you can specify a value for the maximum number of characters it can accommodate. This value is called the capacity of the object and should not be confused with the string length of the current StringBuilder object. For example, you can create a new instance of the StringBuilder class with the string "Hello" (Length: 5) and specify the maximum capacity of this object to 25. When you modify StringBuilder, it does not re-allocate space for itself until the capacity is reached. When the capacity is reached, a new space is automatically allocated and the capacity is doubled. You can use one of the overloaded constructors to specify the capacity of the StringBuilder class. The following code example specifies that the MyStringBuilder object can be expanded to a maximum of 25 white spaces.

Copy codeThe Code is as follows: StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ", 25 );

In addition, you can use the read/write Capacity attribute to set the maximum length of an object. The following code uses the Capacity attribute to define the maximum length of an object.Copy codeThe Code is as follows: MyStringBuilder. Capacity = 25;

The EnsureCapacity method can be used to check the current capacity of the StringBuilder. If the capacity is greater than the passed value, no changes are made. However, if the capacity is smaller than the passed value, the current capacity is changed to match the passed value.

You can also view or set the Length attribute. If you set the Length attribute to a value greater than the Capacity attribute, the Capacity attribute is automatically changed to the same value as the Length attribute. If you set the Length attribute to a value smaller than the string Length in the current StringBuilder object, the string is shortened.

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

Use method name
StringBuilder. Append: Append the information to the end of the current StringBuilder.
StringBuilder. AppendFormat replaces the format specifier passed in the string with formatted text.
StringBuilder. Insert inserts a string or object into the specified index of the current StringBuilder object.
StringBuilder. Remove removes a specified number of characters from the current StringBuilder object.
StringBuilder. Replace replaces the specified character at the specified index.

Append
The Append method can be used to add the string representation of a text or object to the end of a string represented by the current StringBuilder object. In the following example, A StringBuilder object is initialized as "Hello World" and some text is appended to the end of the object. Space will be automatically allocated as needed.

Copy codeThe Code is as follows: StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ");
MyStringBuilder. Append ("What a beautiful day .");
Console. WriteLine (MyStringBuilder );

In this example, Hello World! What a beautiful day. displayed on the console.

AppendFormat
The AppendFormat method adds text to the end of StringBuilder and implements the IFormattable interface. Therefore, the standard format string described in the formatting section is acceptable. You can use this method to customize the variable format and append these values to the end of StringBuilder. The following example uses the AppendFormat method to place an integer set to the currency value format at the end of StringBuilder.

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

In this example, the Your total is $25.00 is displayed on the console.

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

Copy codeThe Code is as follows: StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ");
MyStringBuilder. Insert (6, "Beautiful ");
Console. WriteLine (MyStringBuilder );

In this example, Hello Beautiful World! Displayed on the console.

Remove
You can use the Remove method to Remove a specified number of characters from the current StringBuilder. The removal process starts from the specified index starting from scratch. The following example uses the Remove Method to shorten StringBuilder.

Copy codeThe Code is as follows: StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ");
MyStringBuilder. Remove (5, 7 );
Console. WriteLine (MyStringBuilder );

In this example, Hello is displayed on the console.

Replace
Using the Replace method, you can use another specified character to Replace the characters in the StringBuilder object. The following example uses the Replace method to search for the StringBuilder object and find all exclamation point characters (!), Use the question mark character (?) To replace them.

Copy codeThe Code is as follows: StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ");
MyStringBuilder. Replace ('! ','? ');
Console. WriteLine (MyStringBuilder );

In this example, Hello World? Displayed on the console.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.