16.10. Class StringBuilderThe 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 creating new Strings (e.g., the &= operator creates a new String and assigns it to the String variable on the left side of the operator). The next several sections discuss the features of class StringBuilder (namespace System.Text), used to create and manipulate dynamic string informationthat is, mutable strings. Every StringBuilder can store the number of characters specified by its capacity. Exceeding the capacity of a StringBuilder makes the capacity 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
Performance Tip 16.3
Class StringBuilder provides six overloaded constructors. Class StringBuilderConstructor (Fig. 16.9) demonstrates three of them. Figure 16.9. StringBuilder class constructors.
Line 9 employs the parameterless StringBuilder constructor to create a StringBuilder that contains no characters and has a default initial capacity of 16 characters. Line 10 uses the StringBuilder constructor that takes an Integer argument to create a StringBuilder that contains no characters and has the initial capacity specified in the Integer argument (i.e., 10). Line 11 uses the StringBuilder constructor that takes a String argument to create a StringBuilder containing the characters of the String argument. Theinitial 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 1315 use StringBuilder method ToString to obtain String representations of the StringBuilders' contents. |