![]() CATEGORIES: BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism |
Constructing aStringBuilder ObjectUnlike with the String class, the CLR has no special information about the StringBuilder class. In addition, most languages (including C#) don’t consider the StringBuilder class to be a primitive type. You construct a StringBuilder object as you would any other non-primitive type.
StringBuilder sb = new StringBuilder();
The StringBuilder type offers many constructors. The job of each constructor is to allocate and initialize the state maintained by each StringBuilder object: ■ Maximum capacityAn Int32 value that specifies the maximum number of characters that can be placed in the string. The default is Int32.MaxValue (approximately 2 billion). It’s un- usual to change this value. However, you might specify a smaller maximum capacity to ensure that you never create a string over a certain length. Once constructed, a StringBuilder’s maximum capacity value can’t be changed. ■ CapacityAn Int32 value indicating the size of the character array being maintained by the StringBuilder. The default is 16. If you have some idea of how many characters you’ll place in the StringBuilder, you should use this number to set the capacity when constructing the StringBuilder object. When appending characters to the character array, the StringBuilder detects if the array is trying to grow beyond the array’s capacity. If it is, the StringBuilder automatically doubles the capacity field, allocates a new array (the size of the new capacity), and copies the char- acters from the original array into the new array. The original array will be garbage collected in the future. Dynamically growing the array hurts performance; avoid this by setting a good initial capacity. ■ Character arrayAn array of Char structures that maintains the set of characters in the “string.” The number of characters is always less than or equal to the capacity and maximum capacity values. You can use the StringBuilder’s Length property to obtain the number of characters used in the array. The Length is always less than or equal to the StringBuilder’s capacity value. When constructing a StringBuilder, you can pass a String to initialize the character array. If you don’t specify a string, the array initially contains no characters—that is, the Length property returns 0.
StringBuilder Members Unlike a String, a StringBuilder represents a mutable string. This means that most of String Builder’s members change the contents in the array of characters and don’t cause new objects to be allocated on the managed heap. A StringBuilder allocates a new object on only two occasions: ■ You dynamically build a string whose length is longer than the capacity you’ve set.
■ You call StringBuilder’s ToString method.
Table 14-2 summarizes StringBuilder’s members.
TABLE 14-2StringBuilder Members
One important thing to note about StringBuilder’s methods is that most of them return a refer- ence to the same StringBuilder object. This allows a convenient syntax to chain several operations together.
StringBuilder sb = new StringBuilder(); String s = sb.AppendFormat("{0} {1}", "Jeffrey", "Richter"). Replace(' ', '').Remove(4, 3).ToString(); Console.WriteLine(s); // "JeffRichter"
You’ll notice that the String and StringBuilder classes don’t have full method parity; that is, String has ToLower, ToUpper, EndsWith, PadLeft, PadRight, Trim, and so on. The String Builder class doesn’t offer any of these methods. On the other hand, the StringBuilder class offers a richer Replace method that allows you to replace characters or strings in a portion of the string (not the whole string). It’s unfortunate that there isn’t complete parity between these two classes because now you must convert between String and StringBuilder to accomplish certain tasks. For example, to build up a string, convert all characters to uppercase, and then insert a string requires code like the following.
// Construct a StringBuilder to perform string manipulations. StringBuilder sb = new StringBuilder();
// Perform some string manipulations by using the StringBuilder. sb.AppendFormat("{0} {1}", "Jeffrey", "Richter").Replace(" ", "");
// Convert the StringBuilder to a String in // order to uppercase all the characters. String s = sb.ToString().ToUpper(); // Clear the StringBuilder (allocates a new Char array). sb.Length = 0;
// Load the uppercase String into the StringBuilder, // and perform more manipulations. sb.Append(s).Insert(8, "Marc");
// Convert the StringBuilder back to a String. s = sb.ToString();
// Display the String to the user. Console.WriteLine(s); // "JEFFREYMarcRICHTER"
It’s inconvenient and inefficient to have to write this code just because StringBuilder doesn’t offer all of the operations that String does. In the future, I hope that Microsoft will add more string operation methods to StringBuilder to make it a more complete class.
Date: 2016-03-03; view: 749
|