StringBuilder usage in C # and the difference analysis with string _c# tutorials

Source: Internet
Author: User

The string class has no modification. Each time a character operation is performed, a new string object is created.

The StringBuilder class solves the problem of creating a large number of objects during a repeated modification of a string. After initializing a StringBuilder, it automatically requests a default StringBuilder capacity (the default is 16), which is controlled by capacity. And allow us to control the size of the capacity as needed, You can also get or set the length of the StringBuilder by length.

For example: Write this with the string class

Copy Code code as follows:

String begin_query = "Select UPPER (MachineName) as MachineName," + "LOWER (Machineowner) as Machineowner, Status," + "Startt IME from net_stress WHERE ";

String end_query = "and StartTime > '" + starttime + "' and StartTime < '" + Endtime + "";

String query = begin_query + getwhereclause ("passed") + end_query;

Write this in the StringBuilder class:

Copy Code code 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 a variable with an overloaded constructor method, you can create a new instance of the StringBuilder class, as illustrated in the following example.

Copy Code code 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 the string it encapsulates, you can specify a value for the maximum number of characters it can hold. This value is called the capacity of the object and should not be confused with the length of the string that the current StringBuilder object holds. For example, you can create a new instance of the StringBuilder class with the string "Hello" (length 5), and you can specify that the object's maximum capacity is 25. When StringBuilder is modified, it does not reallocate space for itself until capacity is reached. When capacity is reached, new space is automatically allocated and the capacity doubles. 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 blanks.

Copy Code code as follows:

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.
Copy Code code as follows:

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, but 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 less than the length of the string within the current StringBuilder object, the string is shortened.

modifying StringBuilder strings
The following table lists the methods that you can use to modify the contents of the StringBuilder.

Method Name uses the
Stringbuilder.append appends the information to the end of the current StringBuilder.
Stringbuilder.appendformat replaces the format specifier passed in the string with the formatted text.
Stringbuilder.insert inserts a string or object at the specified index of the current StringBuilder object.
Stringbuilder.remove removes the 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 text or an object to the end of the string represented by the current StringBuilder object. The following example initializes a StringBuilder object to "Hello world" and appends some text to the end of the object. Space is allocated automatically as needed.

Copy Code code as follows:

StringBuilder Mystringbuilder = new StringBuilder ("Hello world!");
Mystringbuilder.append ("What a Beautiful Day.");
Console.WriteLine (Mystringbuilder);

This example will Hello world!   What a beautiful day. displayed to the console.

AppendFormat
The AppendFormat method adds text to the end of the StringBuilder and implements the IFormattable interface, so you can accept the standard format strings described in the Format section. You can use this method to customize the format of a variable and append those values to the back of the StringBuilder. The following example uses the AppendFormat method to place an integer value formatted as a currency value into the end of StringBuilder.

Copy Code code as follows:

int MyInt = 25;
StringBuilder Mystringbuilder = new StringBuilder ("Your Total is");
Mystringbuilder.appendformat ("{0:c}", MyInt);
Console.WriteLine (Mystringbuilder);

This example displays the Your total is $25.00 to 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 into the sixth position of the StringBuilder.

Copy Code code as follows:

StringBuilder Mystringbuilder = new StringBuilder ("Hello world!");
Mystringbuilder.insert (6, "beautiful");
Console.WriteLine (Mystringbuilder);

This example will Hello beautiful world! displayed to the console.

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

Copy Code code as follows:

StringBuilder Mystringbuilder = new StringBuilder ("Hello world!");
Mystringbuilder.remove (5,7);
Console.WriteLine (Mystringbuilder);

This example displays Hello to the console.

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

Copy Code code as follows:

StringBuilder Mystringbuilder = new StringBuilder ("Hello world!");
Mystringbuilder.replace ('! ', '? ');
Console.WriteLine (Mystringbuilder);

This example will be Hello world? displayed to 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.