Sdílet prostřednictvím


StringBuilder Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Represents a mutable string of characters. This class cannot be inherited.

Inheritance Hierarchy

System.Object
  System.Text.StringBuilder

Namespace:  System.Text
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
<ComVisibleAttribute(True)> _
<DefaultMemberAttribute("Chars")> _
Public NotInheritable Class StringBuilder
[ComVisibleAttribute(true)]
[DefaultMemberAttribute("Chars")]
public sealed class StringBuilder

The StringBuilder type exposes the following members.

Constructors

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 StringBuilder() Initializes a new instance of the StringBuilder class.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 StringBuilder(Int32) Initializes a new instance of the StringBuilder class using the specified capacity.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 StringBuilder(String) Initializes a new instance of the StringBuilder class using the specified string.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 StringBuilder(Int32, Int32) Initializes a new instance of the StringBuilder class that starts with a specified capacity and can grow to a specified maximum.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 StringBuilder(String, Int32) Initializes a new instance of the StringBuilder class using the specified string and capacity.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 StringBuilder(String, Int32, Int32, Int32) Initializes a new instance of the StringBuilder class from the specified substring and capacity.

Top

Properties

  Name Description
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Capacity Gets or sets the maximum number of characters that can be contained in the memory allocated by the current instance.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Chars Gets or sets the character at the specified character position in this instance.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Length Gets or sets the length of the current StringBuilder object.

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(Boolean) Appends the string representation of a specified Boolean value to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(Byte) Appends the string representation of a specified 8-bit unsigned integer to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(Char) Appends the string representation of a specified Unicode character to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(array<Char[]) Appends the string representation of the Unicode characters in a specified array to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(Double) Appends the string representation of a specified double-precision floating-point number to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(Int16) Appends the string representation of a specified 16-bit signed integer to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(Int32) Appends the string representation of a specified 32-bit signed integer to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(Int64) Appends the string representation of a specified 64-bit signed integer to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(Object) Appends the string representation of a specified object to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(SByte) Appends the string representation of a specified 8-bit signed integer to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(Single) Appends the string representation of a specified single-precision floating-point number to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(String) Appends a copy of the specified string to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(UInt16) Appends the string representation of a specified 16-bit unsigned integer to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(UInt32) Appends the string representation of a specified 32-bit unsigned integer to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(UInt64) Appends the string representation of a specified 64-bit unsigned integer to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(Char, Int32) Appends a specified number of copies of the string representation of a Unicode character to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(array<Char[], Int32, Int32) Appends the string representation of a specified subarray of Unicode characters to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Append(String, Int32, Int32) Appends a copy of a specified substring to the end of this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 AppendFormat(String, array<Object[]) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a corresponding argument in a parameter array.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 AppendFormat(IFormatProvider, String, array<Object[]) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a corresponding argument in a parameter array using a specified format provider.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 AppendLine() Appends the default line terminator to the end of the current StringBuilder object.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 AppendLine(String) Appends a copy of the specified string and the default line terminator to the end of the current StringBuilder object.
Public methodSupported by Silverlight for Windows Phone Clear Removes all characters from the current StringBuilder instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 EnsureCapacity Ensures that the capacity of this instance of StringBuilder is at least the specified value.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals(StringBuilder) Returns a value indicating whether this instance is equal to a specified object.
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetType Gets the Type of the current instance. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Insert(Int32, array<Char[]) Inserts the string representation of a specified array of Unicode characters into this instance at the specified character position.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Insert(Int32, String) Inserts a string into this instance at the specified character position.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Insert(Int32, String, Int32) Inserts one or more copies of a specified string into this instance at the specified character position.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Insert(Int32, array<Char[], Int32, Int32) Inserts the string representation of a specified subarray of Unicode characters into this instance at the specified character position.
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Remove Removes the specified range of characters from this instance.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Replace(Char, Char) Replaces all occurrences of a specified character in this instance with another specified character.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Replace(String, String) Replaces all occurrences of a specified string in this instance with another specified string.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Replace(Char, Char, Int32, Int32) Replaces, within a substring of this instance, all occurrences of a specified character with another specified character.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Replace(String, String, Int32, Int32) Replaces, within a substring of this instance, all occurrences of a specified string with another specified string.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString() Converts the value of this instance to a String. (Overrides Object.ToString().)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString(Int32, Int32) Converts the value of a substring of this instance to a String.

Top

Remarks

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.

Platform Notes

Silverlight for Windows Phone Silverlight for Windows Phone

 A StringBuilder object can allocate more memory as needed as characters are added to the object. The amount of memory allocated is implementation-specific, and an OutOfMemoryException is thrown if the amount of memory required is not available. If an alternative to StringBuilder is needed, open a MemoryStream and write strings to the memory stream instead of using the StringBuilder class.

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.

Examples

The following code example shows how to call many of the methods defined by the StringBuilder class.

Imports System.Text

Public Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      ' Create a StringBuilder that expects to hold 50 characters.
      ' Initialize the StringBuilder with "ABC".
      Dim sb As New StringBuilder("ABC", 50)

      ' Append three characters (D, E, and F) to the end of the StringBuilder.
      sb.Append(New Char() {"D"c, "E"c, "F"c})

      ' Append a format string to the end of the StringBuilder.
      sb.AppendFormat("GHI{0}{1}", "J"c, "k"c)

      ' Display the number of characters in the StringBuilder and its string.
      outputBlock.Text += String.Format("{0} chars: {1}", sb.Length, sb.ToString()) & vbCrLf

      ' 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.
      outputBlock.Text += String.Format("{0} chars: {1}", sb.Length, sb.ToString()) & vbCrLf
   End Sub
End Module

' This code produces the following output.
'
' 11 chars: ABCDEFGHIJk
' 21 chars: Alphabet: ABCDEFGHIJK
using System;
using System.Text;

public sealed class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // 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' });

      // Exampleend 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.
      outputBlock.Text += String.Format("{0} chars: {1}", sb.Length, sb.ToString()) + "\n";

      // 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.
      outputBlock.Text += String.Format("{0} chars: {1}", sb.Length, sb.ToString()) + "\n";
   }
}

// This code produces the following output.
//
// 11 chars: ABCDEFGHIJk
// 21 chars: Alphabet: ABCDEFGHIJK

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference