Tips for using the StringBuilder class to manipulate strings in C # and the. NET Framework _ Practical Tips

Source: Internet
Author: User

However, if the pros and cons of performance are important, you should always use the StringBuilder class to concatenate strings. The following code uses the Append method of the StringBuilder class to concatenate strings, so there is no link effect of the + operator.

Class Stringbuildertest
{
  static void Main ()
  {
    string text = null;

    Use StringBuilder to concatenation in tight loops.
    System.Text.StringBuilder sb = new System.Text.StringBuilder ();
    for (int i = 0; i < i++)
    {
      sb. Appendline (i.ToString ());
    }
    System.Console.WriteLine (sb.) ToString ());

    Keep the console window open in debug mode.
    System.Console.WriteLine ("Press any key to exit.");
    System.Console.ReadKey ();
  }


Output:

0

1
2
3
4
...

Using the StringBuilder class in the. NET Framework
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 system overhead associated with creating a new string object can be significant if 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, when you concatenate many strings together in a loop, using the StringBuilder class can improve performance.

Instantiating a StringBuilder object
You can create a new instance of the StringBuilder class by initializing the variable with an overloaded constructor method, as illustrated in the following example.

StringBuilder Mystringbuilder = new StringBuilder ("Hello world!");

Set capacity and length
Although StringBuilder is a dynamic object that allows you to expand the number of characters in the string it encapsulates, you can specify the maximum number of characters that an object can hold by using a value. This value is called the capacity of the object and does not confuse it with the length of the string that the current StringBuilder holds. For example, you can use the string "Hello" with a length of 5 to create a new instance of the StringBuilder class, and you can specify that the object has a maximum capacity of 25. When StringBuilder is modified, the object 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 example specifies that the Mystringbuilder object can be expanded to a maximum of 25 blanks.

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 example uses the Capacity property to define the maximum length of an object.

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 is a list of methods that you can use to modify the contents of StringBuilder:
1.stringbuilder.append
Appends the information to the end of the current StringBuilder.
2.stringbuilder.appendformat
Replaces the format specifier passed in the string with the formatted text.
3.stringbuilder.insert
Inserts a string or object at the specified index of the current StringBuilder object.
4.stringbuilder.remove
Removes the specified number of characters from the current StringBuilder object.
5.stringbuilder.replace
Replaces the specified character at the specified index.

1.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.

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

Output:

Hello world! What a beautiful day.

2.AppendFormat
The Stringbuilder.appendformat method adds text to the end of the StringBuilder object. This method supports the composite formatting feature by calling the IFormattable implementation of the object to be formatted (see Composite formatting for more information). Therefore, it accepts numbers, dates and times, and custom format strings for standard format strings, numbers, and date and time values for enumerated values, and format strings that are defined for custom types. (For information about formatting, see Format types in the. NET Framework.) 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 at the end of the StringBuilder object.

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

Output:

Your Total is $25.00  

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

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

Output:

Hello beautiful world!

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

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

Output:

Hello

5.Replace
Use the Replace method to replace characters within a StringBuilder object with another specified character. The following example uses the Replace method to search for all instances of an exclamation character (!) in the StringBuilder object and replaces it with a question mark character (?).

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

Output:

Hello world?

Converts a StringBuilder object to a String
the StringBuilder object must be converted to a string object before the string represented by the StringBuilder object can be passed to a method with a string parameter and displayed in the user interface. You can perform this conversion by calling the Stringbuilder.tostring method. The following example calls many StringBuilder methods and then calls the Stringbuilder.tostring () method to display the string.

Using System;
Using System.Text;

public class Example
{public
  static void Main ()
  {
   StringBuilder sb = new StringBuilder ();
   BOOL flag = TRUE;
   String[] spellings = {"recieve", "Receeve", "receive"};
   Sb. AppendFormat ("Which of the following spellings is {0}:", flag);
   Sb. Appendline ();
   for (int ctr = 0; Ctr <= spellings. GetUpperBound (0); ctr++) {
     sb. AppendFormat ("  {0}"). {1} ", Ctr, Spellings[ctr]);
     Sb. Appendline ();
   }
   Sb. Appendline ();
   Console.WriteLine (sb.) ToString ());
  }


Output:

 Which of the following spellings is true:0. Recieve 1. Receeve 2 Receive 

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.