StringBuilder Class
Represents a mutable string of characters. This class cannot be inherited.
Assembly: mscorlib (in mscorlib.dll)
This class represents a string-like object whose value is a mutable sequence of characters. The value is said to be mutable because it can be modified once it has been created by appending, removing, replacing, or inserting characters. For comparison, see the String class.
Most of the methods that modify an instance of this class return a reference to that same instance. Since a reference to the instance is returned, you can call a method or property on the reference. This can be convenient if you want to write a single statement that chains successive operations one after another.
The capacity of a StringBuilder is the maximum number of characters the instance can store at any given time, and is greater than or equal to the length of the string representation of the value of the instance. The capacity can be increased or decreased with the Capacity property or EnsureCapacity method, but it cannot be less than the value of the Length property.
Implementation-specific default values are used if no capacity or maximum capacity is specified when an instance of StringBuilder is initialized.
Performance Considerations
The Concat and AppendFormat methods both concatenate new data to an existing String or StringBuilder object. A String object concatenation operation always creates a new object from the existing string and the new data. A StringBuilder object maintains a buffer to accommodate the concatenation of new data. New data is appended to the end of the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer.
The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs. A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data. Consequently, the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined into a single operation by the compiler. A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated; for example, if a loop concatenates a random number of strings of user input.
Notes to Implementers:
The default capacity for this implementation is 16, and the default maximum capacity is Int32.MaxValue.
A StringBuilder can allocate more memory as needed to store characters when the value of an instance is enlarged, and the capacity is adjusted accordingly. The amount of memory allocated is implementation-specific, and ArgumentOutOfRangeException is thrown if the amount of memory required is greater than the maximum capacity.
For example, the Append, AppendFormat, EnsureCapacity, Insert, and Replace methods can enlarge the value of an instance.
The individual characters in the value of a StringBuilder can be accessed with the Chars property. Index positions start from zero.
Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE Platform Note: Continuously appending strings to StringBuilder objects can result in virtual address space fragmentation. Due to the limited virtual address space for each process in Windows CE, this issue can appear after appending strings of approximately 3 MB. To workaround this issue, you can set the MaxCapacity property. Alternatively, open a MemoryStream and write strings to the memory stream instead of using the StringBuilder class.
The following example shows how to call many of the methods defined by the StringBuilder class.
using System; using System.Text; public sealed class App { static void Main() { // Create a StringBuilder that expects to hold 50 characters. // Initialize the StringBuilder with "ABC". StringBuilder sb = new StringBuilder("ABC", 50); // Append three characters (D, E, and F) to the end of the StringBuilder. sb.Append(new char[] { 'D', 'E', 'F' }); // Append a format string to the end of the StringBuilder. sb.AppendFormat("GHI{0}{1}", 'J', 'k'); // Display the number of characters in the StringBuilder and its string. Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString()); // Insert a string at the beginning of the StringBuilder. sb.Insert(0, "Alphabet: "); // Replace all lowercase k's with uppercase K's. sb.Replace('k', 'K'); // Display the number of characters in the StringBuilder and its string. Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString()); } } // This code produces the following output. // // 11 chars: ABCDEFGHIJk // 21 chars: Alphabet: ABCDEFGHIJK
Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
# build-string1.ps1
# MSDN Sample using PowerShell
# Thomas Lee - tfl@psp.co.uk
# Create a StringBuilder that expects to hold 50 characters.
# Initialize the StringBuilder with "ABC".
$sb = new-object system.text.stringBuilder "ABC", 50
# Append three characters (D, E, and F) to the end of the StringBuilder.
$resw = $sb.Append("D")
$resw = $sb.Append("E")
$resw = $sb.Append("F")
# Append a format string to the end of the StringBuilder.
$resw = $sb.AppendFormat("GHI{0}{1}", 'J', 'k')
# Display the number of characters in the StringBuilder and its string.
"{0} chars: {1}" -f $sb.Length, $sb.ToString()
# Insert a string at the beginning of the StringBuilder.
$resw = $sb.Insert(0, "Alphabet: ")
# Replace all lowercase k's with uppercase K's.
$resw = $sb.Replace('k', 'K')
# Display the number of characters in the StringBuilder and its string.
"{0} chars: {1}" -f $sb.Length, $sb.ToString()
This script produces the following output:
PS C:\foo> .\build.string1.ps1
11 chars: ABCDEFGHIJk
21 chars: Alphabet: ABCDEFGHIJK
- 8/11/2008
- Thomas Lee
- 3/3/2010
- HMEF
String class is immutable, that means we cannot change the state/value of the string object once it is initialized. So when we try to concatenate two string objects, it creates a new string object and reference of newly created object is returned.
Now, if we use string concatenation in loop, we end up creating 'x' number of new string objects. This will hit our application's performance and memory utilization.
StringBuilder is a mutable string-like class, specifically created for building composite strings effectively. Using this we can avoid creating ‘x’ number of string objects while concatenating strings. StringBuilder comes with methods like Append, AppendFormat, Insert, etc.
- 2/15/2009
- Mujahid Khaleel
To effectively clear your stringbuilder without destroying it use:
someStringBuilder.length = 0;
someStringBuilder.capacity = 0;
This destroys both its contents and resizes it to zero.
As noted above clear the size can impact smaller applications.
Added benefit: If your application support a very large number of users (i.e. Microsoft's Sites like Live.com) this will ensure the most efficient use of system memory without relying on gargabe collection.
- 11/12/2008
- Mr. Davies
Setting the .Length property of the string builder will truncate the contents down to the length you specified. Lets look at this simple example:
Example
StringBuilder sb = new StringBuilder(5); // .Length = 5
sb.Append("01234567890123456789"); // Forces .Length = 20
sb.Length = 10; // Truncates the string down to 0-9 (hence .Length = 10)
sb.Append("AB"); // Makes .Length = 12 since it appends two more
Console.WriteLine("Length = {0}", sb.Length); // Prints 12
Console.WriteLine("Capacity = {0}", sb.Capacity); // Print 20
Console.ReadKey();
The example above will produce 12 as the Length, and 20 as the capacity. See the code comments to understand what is happening
- 3/24/2008
- LyalinDotCom