Class StringBuilder

The string class provides many capabilities for processing strings. However a string's contents can never change. Operations that seem to concatenate strings are in fact assigning string references to newly created strings (e.g., the += operator creates a new string and assigns the initial string reference to the newly created string).

The next several sections discuss the features of class StringBuilder (namespace System.Text), used to create and manipulate dynamic string informationi.e., mutable strings. Every StringBuilder can store a certain number of characters that is specified by its capacity. Exceeding the capacity of a StringBuilder causes the capacity to expand to accommodate the additional characters. As we will see, members of class StringBuilder, such as methods Append and AppendFormat, can be used for concatenation like the operators + and += for class string.

Performance Tip 16 2

Objects of class string are immutable (i.e., constant strings), whereas object of class StringBuilder are mutable. C# can perform certain optimizations involving strings (such as the sharing of one string among multiple references), because it knows these objects will not change.

Class StringBuilder provides six overloaded constructors. Class StringBuilderConstructor (Fig. 16.9) demonstrates three of these overloaded constructors.

Figure 16.9. StringBuilder class constructors.

1 // Fig. 16.9: StringBuilderConstructor.cs 2 // Demonstrating StringBuilder class constructors. 3 using System; 4 using System.Text; 5 6 class StringBuilderConstructor 7 8 public static void Main() 9 { 10 StringBuilder buffer1, buffer2, buffer3; 11 12 buffer1 = new StringBuilder(); 13 buffer2 = new StringBuilder( 10 ); 14 buffer3 = new StringBuilder( "hello" ); 15 16 Console.WriteLine( "buffer1 = "" + buffer1 + """ ); 17 Console.WriteLine( "buffer2 = "" + buffer2 + """ ); 18 Console.WriteLine( "buffer3 = "" + buffer3 + """ ); 19 } // end method Main 20 } // end class StringBuilderConstructor  

buffer1 = "" buffer2 = "" buffer3 = "hello"

Line 12 employs the no-parameter StringBuilder constructor to create a StringBuilder that contains no characters and has a default initial capacity of 16 characters. Line 13 uses the StringBuilder constructor that takes an int argument to create a StringBuilder that contains no characters and has the initial capacity specified in the int argument (i.e., 10). Line 14 uses the StringBuilder constructor that takes a string argument to create a StringBuilder containing the characters of the string argument. The initial capacity is the smallest power of two greater than or equal to the number of characters in the argument string, with a minimum of 16. Lines 1618 implicitly use StringBuilder method ToString to obtain string representations of the StringBuilders' contents.

Категории