See Also: StringBuilder Members
This class represents a string-like object whose value is a mutable sequence of characters.
In this section:
Although System.Text.StringBuilder and string both represent sequences of characters, they are implemented differently. string is an immutable type. That is, each operation that appears to modify a string object actually creates a new string.
For example, the call to the string.Concat(String) method in the following C# example appears to change the value of a string variable named value. In fact, the string.Concat(String) method returns a value object that has a different value and address from the value object that was passed to the method. Note that the example must be compiled using the /unsafe compiler option.
code reference: System.Text.StringBuilder.Class#1
For routines that perform extensive string manipulation (such as apps that modify a string numerous times in a loop), modifying a string repeatedly can exact a significant performance penalty. The alternative is to use System.Text.StringBuilder, which is a mutable string class. Mutability means that once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters. A System.Text.StringBuilder object maintains a buffer to accommodate expansions to the string. New data is appended to the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, and the new data is then appended to the new buffer.
Although the System.Text.StringBuilder class generally offers better performance than the string class, you should not automatically replace string with System.Text.StringBuilder whenever you want to manipulate strings. Performance depends on the size of the string, the amount of memory to be allocated for the new string, the system on which your app is executing, and the type of operation. You should be prepared to test your app to determine whether System.Text.StringBuilder actually offers a significant performance improvement.
Consider using the string class under these conditions:
When you are performing a fixed number of concatenation operations, particularly with string literals. In this case, the compiler might combine the concatenation operations into a single operation.
When you have to perform extensive search operations while you are building your string. The System.Text.StringBuilder class lacks search methods such as IndexOf or StartsWith. You'll have to convert the System.Text.StringBuilder object to a string for these operations, and this can negate the performance benefit from using System.Text.StringBuilder. For more information, see the Searching the text in a StringBuilder object section.
Consider using the System.Text.StringBuilder class under these conditions:
When you expect your app to make an unknown number of changes to a string at design time (for example, when you are using a loop to concatenate a random number of strings that contain user input).
When you expect your app to make a significant number of changes to a string.
The StringBuilder.Length property indicates the number of characters the System.Text.StringBuilder object currently contains. If you add characters to the System.Text.StringBuilder object, its length increases until it equals the size of the StringBuilder.Capacity property, which defines the number of characters that the object can contain. If the number of added characters causes the length of the System.Text.StringBuilder object to exceed its current capacity, new memory is allocated, the value of the StringBuilder.Capacity property is doubled, new characters are added to the System.Text.StringBuilder object, and its StringBuilder.Length property is adjusted. Additional memory for the System.Text.StringBuilder object is allocated dynamically until it reaches the value defined by the StringBuilder.MaxCapacity property. When the maximum capacity is reached, no further memory can be allocated for the System.Text.StringBuilder object, and trying to add characters or expand it beyond its maximum capacity throws either an ArgumentOutOfRangeException or an OutOfMemoryException exception.
The following example illustrates how a System.Text.StringBuilder object allocates new memory and increases its capacity dynamically as the string assigned to the object expands. The code creates a System.Text.StringBuilder object by calling its default (parameterless) constructor. The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters. Appending the string "This is a sentence." results in a new memory allocation because the string length (19 characters) exceeds the default capacity of the System.Text.StringBuilder object. The capacity of the object doubles to 32 characters, the new string is added, and the length of the object now equals 19 characters. The code then appends the string "This is an additional sentence." to the value of the System.Text.StringBuilder object 11 times. Whenever the append operation causes the length of the System.Text.StringBuilder object to exceed its capacity, its existing capacity is doubled and the StringBuilder.Append(string) operation succeeds.
code reference: System.Text.StringBuilder.Class#3
The default capacity of a System.Text.StringBuilder object is 16 characters, and its default maximum capacity is int.MaxValue. These default values are used if you call the StringBuilder.#ctor and StringBuilder.#ctor(string) constructors.
You can explicitly define the initial capacity of a System.Text.StringBuilder object in the following ways:
By calling any of the System.Text.StringBuilder constructors that includes a capacity parameter when you create the object.
By explicitly assigning a new value to the StringBuilder.Capacity property to expand an existing System.Text.StringBuilder object. Note that the property throws an exception if the new capacity is less than the existing capacity or greater than the System.Text.StringBuilder object's maximum capacity.
By calling the StringBuilder.EnsureCapacity(int) method with the new capacity. The new capacity must not be greater than the System.Text.StringBuilder object's maximum capacity. However, unlike an assignment to the StringBuilder.Capacity property, StringBuilder.EnsureCapacity(int) does not throw an exception if the desired new capacity is less than the existing capacity; in this case, the method call has no effect.
If the length of the string assigned to the System.Text.StringBuilder object in the constructor call exceeds either the default capacity or the specified capacity, the StringBuilder.Capacity property is set to the length of the string specified with the value parameter.
You can explicitly define the maximum capacity of a System.Text.StringBuilder object by calling the StringBuilder.#ctor(int, int) constructor. You can't change the maximum capacity by assigning a new value to the StringBuilder.MaxCapacity property, because it is read-only.
As the previous section shows, whenever the existing capacity is inadequate, additional memory is allocated and the capacity of a System.Text.StringBuilder object doubles up to the value defined by the StringBuilder.MaxCapacity property.
In general, the default capacity and maximum capacity are adequate for most apps. You might consider setting these values under the following conditions:
If the eventual size of the System.Text.StringBuilder object is likely to grow exceedingly large, typically in excess of several megabytes. In this case, there may be some performance benefit from setting the initial StringBuilder.Capacity property to a significantly high value to eliminate the need for too many memory reallocations.
If your app is running on a system with limited memory. In this case, you may want to consider setting the StringBuilder.MaxCapacity property to less than int.MaxValue if your app is handling large strings that may cause it to execute in a memory-constrained environment.
You instantiate a System.Text.StringBuilder object by calling one of its six overloaded class constructors, which are listed in the following table. Three of the constructors instantiate a System.Text.StringBuilder object whose value is an empty string, but set its StringBuilder.Capacity and StringBuilder.MaxCapacity values differently. The remaining three constructors define a System.Text.StringBuilder object that has a specific string value and capacity. Two of the three constructors use the default maximum capacity of int.MaxValue, whereas the third allows you to set the maximum capacity.
Defined by the capacity parameter
Defined by the capacity parameter
Defined by the maxCapacity parameter
Defined by the value parameter
16 or value. string.Length, whichever is greater
Defined by the value parameter
Defined by the capacity parameter or value. string.Length, whichever is greater.
|StringBuilder.#ctor(string, int, int, int)||
Defined by value. string.Substring(int)(startIndex, length)
Defined by the capacity parameter or value. string.Length, whichever is greater.
Defined by the maxCapacity parameter
The following example uses three of these constructor overloads to instantiate System.Text.StringBuilder objects.
code reference: System.Text.StringBuilder.Class#6
You can make individual method calls and ignore the return value, as the following example does.
code reference: System.Text.StringBuilder.Class#4
You can make a series of method calls in a single statement. This can be convenient if you want to write a single statement that chains successive operations. The following example consolidates three method calls from the previous example into a single line of code.
code reference: System.Text.StringBuilder.Class#5
You can access the characters in a System.Text.StringBuilder object by using the StringBuilder.Chars(int) property. In C#, StringBuilder.Chars(int) is an indexer; in Visual Basic, it is the default property of the System.Text.StringBuilder class. This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the StringBuilder.Chars(int) property. Characters in a System.Text.StringBuilder object begin at index 0 (zero) and continue to index StringBuilder.Length - 1.
The following example illustrates the StringBuilder.Chars(int) property. It appends ten random numbers to a System.Text.StringBuilder object, and then iterates each character. If the character's Unicode category is System.Globalization.UnicodeCategory.DecimalDigitNumber, it decreases the number by 1 (or changes the number to 9 if its value is 0). The example displays the contents of the System.Text.StringBuilder object both before and after the values of individual characters were changed.
code reference: System.Text.StringBuilder.Class#7
The StringBuilder.Append(string) method appends a string, a substring, a character array, a portion of a character array, a single character repeated multiple times, or the string representation of a primitive data type to a System.Text.StringBuilder object.
The StringBuilder.AppendFormat(string, Object) method appends a composite format string to a System.Text.StringBuilder object. The string representations of objects included in the result string can reflect the formatting conventions of the current system culture or a specified culture.
The StringBuilder.Insert(int, string) method inserts a string, a substring, multiple repetitions of a string, a character array, a portion of a character array, or the string representation of a primitive data type at a specified position in the System.Text.StringBuilder object. The position is defined by a zero-based index.
The following example uses the StringBuilder.Append(string), StringBuilder.AppendLine, StringBuilder.AppendFormat(string, Object), and StringBuilder.Insert(int, string) methods to expand the text of a System.Text.StringBuilder object.
code reference: System.Text.StringBuilder.Class#9
The System.Text.StringBuilder class includes methods that can reduce the size of the current System.Text.StringBuilder instance. The StringBuilder.Clear method removes all characters and sets the StringBuilder.Length property to zero. The StringBuilder.Remove(int, int) method deletes a specified number of characters starting at a particular index position. In addition, you can remove characters from the end of a System.Text.StringBuilder object by setting its StringBuilder.Length property to a value that is less than the length of the current instance.
The following example removes some of the text from a System.Text.StringBuilder object, displays its resulting capacity, maximum capacity, and length property values, and then calls the StringBuilder.Clear method to remove all the characters from the System.Text.StringBuilder object.
code reference: System.Text.StringBuilder.Class#10
The StringBuilder.Replace(string, string) method replaces all occurrences of a character or a string in the entire System.Text.StringBuilder object or in a particular character range. The following example uses the StringBuilder.Replace(string, string) method to replace all exclamation points (!) with question marks (?) in the System.Text.StringBuilder object.
code reference: System.Text.StringBuilder.Class#11
The System.Text.StringBuilder class does not include methods similar to the string.Contains(string), string.IndexOf(string), and string.StartsWith(string) methods provided by the string class, which allow you to search the object for a particular character or a substring. Determining the presence or starting character position of a substring requires that you search a string value by using either a string search method or a regular expression method. There are four ways to implement such searches, as the following table shows.
|Search string values before adding them to the System.Text.StringBuilder object.||
Useful for determining whether a substring exists.
Cannot be used when the index position of a substring is important.
|Call StringBuilder.ToString and search the returned string object.||
Easy to use if you assign all the text to a System.Text.StringBuilder object, and then begin to modify it.
You must remember to work from the end of the System.Text.StringBuilder object's text if you're making changes.
|Use the StringBuilder.Chars(int) property to sequentially search a range of characters.||
Useful if you're concerned with individual characters or a small substring.
Cumbersome if the number of characters to search is large or if the search logic is complex.
|Convert the System.Text.StringBuilder object to a string object, and perform modifications on the string object.||
Useful if the number of modifications is small.
Negates the performance benefit of the System.Text.StringBuilder class if the number of modifications is large.
Let's examine these techniques in greater detail.
If the goal of the search is to determine whether a particular substring exists (that is, if you aren't interested in the position of the substring), you can search strings before storing them in the System.Text.StringBuilder object. The following example provides one possible implementation. It defines a StringBuilderFinder class whose constructor is passed a reference to a System.Text.StringBuilder object and the substring to find in the string. In this case, the example tries to determine whether recorded temperatures are in Fahrenheit or Celsius, and adds the appropriate introductory text to the beginning of the System.Text.StringBuilder object. A random number generator is used to select an array that contains data in either degrees Celsius or degrees Fahrenheit.
code reference: System.Text.StringBuilder.Class#12
Call the StringBuilder.ToString method to convert the System.Text.StringBuilder object to a string object. You can search the string by using methods such as string.LastIndexOf(string) or string.StartsWith(string), or you can use regular expressions and the System.Text.RegularExpressions.Regex class to search for patterns. Because both System.Text.StringBuilder and string objects use UTF-16 encoding to store characters, the index positions of characters, substrings, and regular expression matches are the same in both objects. This enables you to use System.Text.StringBuilder methods to make changes at the same position at which that text is found in the string object.
The following example illustrates this approach. It stores four occurrences of each letter of the English alphabet in a System.Text.StringBuilder object. It then converts the text to a string object and uses a regular expression to identify the starting position of each four-character sequence. Finally, it adds an underscore before each four-character sequence except for the first sequence, and converts the first character of the sequence to uppercase.
code reference: System.Text.StringBuilder.Class#13
Use the StringBuilder.Chars(int) property to sequentially search a range of characters in a System.Text.StringBuilder object. This approach may not be practical if the number of characters to be searched is large or the search logic is particularly complex.
The following example is identical in functionality to the previous example but differs in implementation. It uses the StringBuilder.Chars(int) property to detect when a character value has changed, inserts an underscore at that position, and converts the first character in the new sequence to uppercase.
code reference: System.Text.StringBuilder.Class#14
Store all the unmodified text in the System.Text.StringBuilder object, call the StringBuilder.ToString method to convert the System.Text.StringBuilder object to a string object, and perform the modifications on the string object. You can use this approach if you have only a few modifications; otherwise, the cost of working with immutable strings may negate the performance benefits of using a System.Text.StringBuilder object.
The following example is identical in functionality to the previous two examples but differs in implementation. It creates a System.Text.StringBuilder object, converts it to a string object, and then uses a regular expression to perform all remaining modifications on the string. The System.Text.RegularExpressions.Regex.Replace(string, string, System.Text.RegularExpressions.MatchEvaluator) method uses a lambda expression to perform the replacement on each match.
code reference: System.Text.StringBuilder.Class#15
You must convert the System.Text.StringBuilder object to a string object before you can pass the string represented by the System.Text.StringBuilder object to a method that has a string parameter or display it in the user interface. You perform this conversion by calling the StringBuilder.ToString method. For an illustration, see the previous example, which calls the StringBuilder.ToString method to convert a System.Text.StringBuilder object to a string so that it can be passed to a regular expression method.