Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Constructing aStringBuilder Object

Unlike 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

 

Member Member Type Description
MaxCapacity Read-only property Returns the largest number of characters that can be placed in the string.
Capacity Read/write property Gets or sets the size of the character array. Trying to set the capac- ity smaller than the string’s length or bigger than MaxCapacity throws an ArgumentOutOfRangeException.
EnsureCapacity Method Guarantees that the character array is at least the size specified. If the value passed is larger than the StringBuilder’s current capacity, the current capacity increases. If the current capacity is already larger than the value passed to this method, no change occurs.
Length Read/write property Gets or sets the number of characters in the “string.” This will likely be smaller than the character array’s current capacity. Setting this property to 0 resets the StringBuilder’s contents to an empty string.
ToString Method The parameterless version of this method returns a String rep- resenting the StringBuilder’s character array.
Chars Read/write indexer property Gets or sets the character at the specified index into the character array. In C#, this is an indexer (parameterful property) that you access using array syntax ([]).
Clear Method Clears the contents of the StringBuilder object, the same as setting its Length property to 0.

Member Member Type Description
Append Method Appends a single object to the end of the character array, growing the array if necessary. The object is converted to a string by us- ing the general format and the culture associated with the calling thread.
Insert Method Inserts a single object into the character array, growing the array if necessary. The object is converted to a string by using the general format and the culture associated with the calling thread.
AppendFormat Method Appends the specified objects to the end of the character ar- ray, growing the array if necessary. The objects are converted to strings by using the formatting and culture information provided by the caller. AppendFormat is one of the most common meth- ods used with StringBuilder objects.
AppendLine Method Appends a blank line or a string with a blank line to the end of the character array, increasing the capacity of the array if necessary.
Replace Method Replaces one character with another or one string with another from within the character array.
Remove Method Removes a range of characters from the character array.
Equals Method Returns true only if both StringBuilder objects have the same maximum capacity, capacity, and characters in the array.
CopyTo Method Copies a subset of the StringBuilder’s characters to a Char array.

 



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); // "Jeff­Richter"

 

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); // "JEFFREY­Marc­RICHTER"

 

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: 662


<== previous page | next page ==>
Nbsp;   The System.String Type | Nbsp;   Obtaining a String Representation of an Object: ToString
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.009 sec.)