Basic usage of the stringbuilder type in. Net/C #

Source: Internet
Author: User

Stringbuilder uses the constructor design mode to efficiently construct a String object. during the construction process, stringbuilder can effectively avoid the generation of temporary string objects.

 

1: When you need to operate a long string or perform frequent operations on the string, use stringbuilder. In other cases, it is easier to use string.

2: It is generally easier to use string because:

Stringbuilder sb = "Hello world! "; Such a statement cannot be used:

Stringbuilder sb = new stringbuilder ("Hello world! "); In this way, a stringbuilder object can be initialized.

 

SB = "change the content of stringbuilder"; this statement is not acceptable. You cannot directly convert the string to stringbuilder. explicit conversion is not acceptable!

 

SB. Remove (0, SB. Length );
SB. append ("Test for string builder change! "); In this way, the content of a stringbuilder object can be changed. Or use the SB. Replace (); method.

 

3: The stringbuilder class also has this feature: Its Length attribute is not readonly,

Suppose there are: stringbuilder sb = new stringbuilder ("12345 ");

Run: SB. Length = 3;

Then output the Sb content, and only 123 is left. If the length is greater than the original length, fill in spaces.

The string type does not have this function. Its length is read only!

 

"The stringbuilder class retains a private member of the string type. When the tostring () method is called, the member of the string type is assigned a value and returned to the caller. During string assembly, the string will be directly modified in memory. Stringbuilderod not only provides better performance string operations, but also can be used to interact with unmanaged code. For unmanaged code, string operations are directly based on memory. If you use string-type and unmanaged code, it may violate the principle of immutable string objects. Therefore, the stringbuilder class is often used to interact with unmanaged code ."

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.