StringBuilder StringBuilder StringBuilder StringBuilder Class

定義

表示可變動的字元字串。Represents a mutable string of characters. 這個類別無法被繼承。This class cannot be inherited.

public ref class StringBuilder sealed : System::Runtime::Serialization::ISerializable
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class StringBuilder : System.Runtime.Serialization.ISerializable
type StringBuilder = class
    interface ISerializable
Public NotInheritable Class StringBuilder
Implements ISerializable
繼承
StringBuilderStringBuilderStringBuilderStringBuilder
屬性
實作

範例

下列範例示範如何呼叫所定義之方法的許多StringBuilder類別。The following example shows how to call many of the methods defined by the StringBuilder class.

using namespace System;
using namespace System::Text;

int main()
{
    // Create a StringBuilder that expects to hold 50 characters.
    // Initialize the StringBuilder with "ABC".
    StringBuilder^ sb = gcnew StringBuilder("ABC", 50);

    // Append three characters (D, E, and F) to the end of the
    // StringBuilder.
    sb->Append(gcnew array<Char>{'D', 'E', 'F'});

    // Append a format string to the end of the StringBuilder.
    sb->AppendFormat("GHI{0}{1}", (Char)'J', (Char)'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
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
Imports System.Text

Public Module App 
    Public Sub Main() 
        ' 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.
        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())
    End Sub
End Module

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

備註

此類別代表字串相似的物件,其值是可變動的一連串的字元。This class represents a string-like object whose value is a mutable sequence of characters.

本節內容:In this section:

String 和 StringBuilder 類型The String and StringBuilder types

雖然StringBuilderString都代表序列的字元,它們的實作方式不同。Although StringBuilder and String both represent sequences of characters, they are implemented differently. String 是不可變的類型。String is an immutable type. 也就是每個作業顯示修改String物件實際上會建立新的字串。That is, each operation that appears to modify a String object actually creates a new string.

例如,呼叫String.Concat方法,在下列 C# 範例中會出現名為的字串變數的值變更valueFor example, the call to the String.Concat method in the following C# example appears to change the value of a string variable named value. 事實上,Concat方法會傳回value物件,具有不同的值和位址value已傳遞給方法的物件。In fact, the Concat method returns a value object that has a different value and address from the value object that was passed to the method. 請注意,必須使用編譯範例/unsafe編譯器選項。Note that the example must be compiled using the /unsafe compiler option.

using System;

public class Example
{
   public unsafe static void Main()
   {
      string value = "This is the first sentence" + ".";
      fixed (char* start = value)
      {
         value = String.Concat(value, "This is the second sentence. ");
         fixed (char* current = value)
         {
            Console.WriteLine(start == current);
         }
      }   
   }
}
// The example displays the following output:
//      False

針對執行大量的字串操作 (例如修改許多時間在迴圈中的字串的應用程式) 的常式,重複修改字串可以精確顯著的效能負面影響。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. 替代方法是使用StringBuilder,這是可變動字串類別。The alternative is to use 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. AStringBuilder物件會維護緩衝區來容納展開為字串。A 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.

重要

雖然StringBuilder類別通常提供較佳的效能比String類別,您應該不會自動取代String使用StringBuilder每當您想要操作字串。Although the StringBuilder class generally offers better performance than the String class, you should not automatically replace String with 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. 您應該已準備好測試您的應用程式,以判斷是否StringBuilder確實會提供顯著的效能改善。You should be prepared to test your app to determine whether StringBuilder actually offers a significant performance improvement.

請考慮使用String在這些情況下的類別:Consider using the String class under these conditions:

  • 當您的應用程式將會對字串進行的變更數目很小。When the number of changes that your app will make to a string is small. 在這些情況下,StringBuilder可能不明顯的供應項目或沒有效能改進StringIn these cases, StringBuilder might offer negligible or no performance improvement over String.

  • 當您執行固定的數目的串連作業中,特別是使用字串常值。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. StringBuilder搜尋方法,例如類別缺少IndexOfStartsWithThe StringBuilder class lacks search methods such as IndexOf or StartsWith. 您必須轉換StringBuilder物件至String針對這些作業,而這可以變換正負號的效能優勢,從使用StringBuilderYou'll have to convert the StringBuilder object to a String for these operations, and this can negate the performance benefit from using StringBuilder. 如需詳細資訊,請參閱 < StringBuilder 物件中搜尋文字一節。For more information, see the Searching the text in a StringBuilder object section.

請考慮使用StringBuilder在這些情況下的類別:Consider using the 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.

StringBuilder 的運作方式How StringBuilder works

StringBuilder.Length屬性指示的字元數StringBuilder目前包含的物件。The StringBuilder.Length property indicates the number of characters the StringBuilder object currently contains. 如果您新增字元StringBuilder物件,其長度會增加,直到它等於大小StringBuilder.Capacity屬性,定義的物件可以包含的字元數。If you add characters to the 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. 如果加入的字元數的長度StringBuilder超過其目前的容量,新的記憶體配置物件,值Capacity屬性會增加一倍,新的字元會新增至StringBuilder物件和其Length屬性會進行調整。If the number of added characters causes the length of the StringBuilder object to exceed its current capacity, new memory is allocated, the value of the Capacity property is doubled, new characters are added to the StringBuilder object, and its Length property is adjusted. 額外的記憶體供StringBuilder物件,直到它到達所定義的值以動態方式配置StringBuilder.MaxCapacity屬性。Additional memory for the StringBuilder object is allocated dynamically until it reaches the value defined by the StringBuilder.MaxCapacity property. 當到達最大容量時,沒有進一步的記憶體可配置給StringBuilder物件,並嘗試新增的字元,或擴充到超過其最大的容量會擲回其中一個ArgumentOutOfRangeExceptionOutOfMemoryException例外狀況。When the maximum capacity is reached, no further memory can be allocated for the StringBuilder object, and trying to add characters or expand it beyond its maximum capacity throws either an ArgumentOutOfRangeException or an OutOfMemoryException exception.

下列範例說明如何StringBuilder物件配置新的記憶體,並會以動態方式增加其容量,因為指派給物件的字串會展開。The following example illustrates how a StringBuilder object allocates new memory and increases its capacity dynamically as the string assigned to the object expands. 程式碼會建立StringBuilder藉由呼叫其預設 (無參數) 建構函式的物件。The code creates a StringBuilder object by calling its default (parameterless) constructor. 此物件的預設容量 16 個字元,且其最大容量為超過 2 億個字元。The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters. 附加字串"This is 句子"。Appending the string "This is a sentence." 產生新的記憶體配置,因為字串長度 (19 個字元) 超過預設容量StringBuilder物件。results in a new memory allocation because the string length (19 characters) exceeds the default capacity of the StringBuilder object. 物件的容量加倍為 32 個字元、 加入新的字串,以及物件的長度現在等於 19 個字元。The capacity of the object doubles to 32 characters, the new string is added, and the length of the object now equals 19 characters. 程式碼則會附加字串"This is 其他句子"。The code then appends the string "This is an additional sentence." StringBuilder物件 11 倍。to the value of the StringBuilder object 11 times. 每當附加作業會導致長度StringBuilder超過其容量,其現有容量的物件會增加一倍和Append作業成功。Whenever the append operation causes the length of the StringBuilder object to exceed its capacity, its existing capacity is doubled and the Append operation succeeds.

using System;
using System.Reflection;
using System.Text;

public class Example
{
   public static void Main()
   {
      StringBuilder sb = new StringBuilder();
      ShowSBInfo(sb);
      sb.Append("This is a sentence.");
      ShowSBInfo(sb);
      for (int ctr = 0; ctr <= 10; ctr++) {
         sb.Append("This is an additional sentence.");
         ShowSBInfo(sb);
      }   
   }
   
   private static void ShowSBInfo(StringBuilder sb)
   {
      foreach (var prop in sb.GetType().GetProperties()) {
         if (prop.GetIndexParameters().Length == 0)
            Console.Write("{0}: {1:N0}    ", prop.Name, prop.GetValue(sb));
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    Capacity: 16    MaxCapacity: 2,147,483,647    Length: 0
//    Capacity: 32    MaxCapacity: 2,147,483,647    Length: 19
//    Capacity: 64    MaxCapacity: 2,147,483,647    Length: 50
//    Capacity: 128    MaxCapacity: 2,147,483,647    Length: 81
//    Capacity: 128    MaxCapacity: 2,147,483,647    Length: 112
//    Capacity: 256    MaxCapacity: 2,147,483,647    Length: 143
//    Capacity: 256    MaxCapacity: 2,147,483,647    Length: 174
//    Capacity: 256    MaxCapacity: 2,147,483,647    Length: 205
//    Capacity: 256    MaxCapacity: 2,147,483,647    Length: 236
//    Capacity: 512    MaxCapacity: 2,147,483,647    Length: 267
//    Capacity: 512    MaxCapacity: 2,147,483,647    Length: 298
//    Capacity: 512    MaxCapacity: 2,147,483,647    Length: 329
//    Capacity: 512    MaxCapacity: 2,147,483,647    Length: 360
Imports System.Reflection
Imports System.Text

Module Example
   Public Sub Main()
      Dim sb As New StringBuilder()
      ShowSBInfo(sb)
      sb.Append("This is a sentence.")
      ShowSbInfo(sb)
      For ctr As Integer = 0 To 10
         sb.Append("This is an additional sentence.")
         ShowSbInfo(sb)
      Next   
   End Sub
   
   Public Sub ShowSBInfo(sb As StringBuilder)
      For Each prop In sb.GetType().GetProperties
         If prop.GetIndexParameters().Length = 0 Then
            Console.Write("{0}: {1:N0}    ", prop.Name, prop.GetValue(sb))
         End If   
      Next
      Console.WriteLine()
   End Sub
End Module
' The example displays the following output:
'    Capacity: 16    MaxCapacity: 2,147,483,647    Length: 0
'    Capacity: 32    MaxCapacity: 2,147,483,647    Length: 19
'    Capacity: 64    MaxCapacity: 2,147,483,647    Length: 50
'    Capacity: 128    MaxCapacity: 2,147,483,647    Length: 81
'    Capacity: 128    MaxCapacity: 2,147,483,647    Length: 112
'    Capacity: 256    MaxCapacity: 2,147,483,647    Length: 143
'    Capacity: 256    MaxCapacity: 2,147,483,647    Length: 174
'    Capacity: 256    MaxCapacity: 2,147,483,647    Length: 205
'    Capacity: 256    MaxCapacity: 2,147,483,647    Length: 236
'    Capacity: 512    MaxCapacity: 2,147,483,647    Length: 267
'    Capacity: 512    MaxCapacity: 2,147,483,647    Length: 298
'    Capacity: 512    MaxCapacity: 2,147,483,647    Length: 329
'    Capacity: 512    MaxCapacity: 2,147,483,647    Length: 360

記憶體配置Memory allocation

預設容量StringBuilder物件是 16 個字元,而它的預設最大容量Int32.MaxValueThe default capacity of a StringBuilder object is 16 characters, and its default maximum capacity is Int32.MaxValue. 如果您呼叫,會使用這些預設值StringBuilder()StringBuilder(String)建構函式。These default values are used if you call the StringBuilder() and StringBuilder(String) constructors.

您可以明確定義的初始容量StringBuilder物件如下:You can explicitly define the initial capacity of a StringBuilder object in the following ways:

  • 藉由呼叫任一StringBuilder建構函式,其中包含capacity參數,當您建立的物件。By calling any of the StringBuilder constructors that includes a capacity parameter when you create the object.

  • 藉由明確地指派新的值,以StringBuilder.Capacity要展開的現有屬性StringBuilder物件。By explicitly assigning a new value to the StringBuilder.Capacity property to expand an existing StringBuilder object. 請注意,屬性會擲回例外狀況的新容量是否小於現有容量或更高StringBuilder物件的最大容量。Note that the property throws an exception if the new capacity is less than the existing capacity or greater than the StringBuilder object's maximum capacity.

  • 藉由呼叫StringBuilder.EnsureCapacity使用新的容量的方法。By calling the StringBuilder.EnsureCapacity method with the new capacity. 新的容量不能大於StringBuilder物件的最大容量。The new capacity must not be greater than the StringBuilder object's maximum capacity. 不過,與指派給不同Capacity屬性,EnsureCapacity如果不擲回例外狀況所需的新容量小於現有容量; 方法呼叫在此情況下,沒有任何作用。However, unlike an assignment to the Capacity property, EnsureCapacity 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.

如果字串的長度會指派給StringBuilder建構函式呼叫中的物件超過預設容量或指定的容量Capacity屬性設定為與指定之字串的長度value參數。If the length of the string assigned to the StringBuilder object in the constructor call exceeds either the default capacity or the specified capacity, the Capacity property is set to the length of the string specified with the value parameter.

您可以明確定義的最大容量StringBuilder藉由呼叫物件StringBuilder(Int32, Int32)建構函式。You can explicitly define the maximum capacity of a StringBuilder object by calling the StringBuilder(Int32, Int32) constructor. 您無法變更的最大容量指派新值給MaxCapacity屬性,因為它是唯讀的。You can't change the maximum capacity by assigning a new value to the MaxCapacity property, because it is read-only.

如上一節所示,每當現有容量不足、 其他記憶體配置和容量StringBuilder物件所定義之值以前的雙精度浮點數MaxCapacity屬性。As the previous section shows, whenever the existing capacity is inadequate, additional memory is allocated and the capacity of a StringBuilder object doubles up to the value defined by the 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:

  • 如果的最終大小StringBuilder物件很可能會變得非常大,通常會超過數個 mb。If the eventual size of the StringBuilder object is likely to grow exceedingly large, typically in excess of several megabytes. 在此情況下,可能會有一些效能優點,設定初始Capacity屬性設為高的值,以便不需要太多記憶體重新配置。In this case, there may be some performance benefit from setting the initial 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. 在此情況下,您可能要考慮MaxCapacity屬性小於Int32.MaxValue如果您的應用程式正在處理可能會導致它在記憶體限制的環境中執行的大型字串。In this case, you may want to consider setting the MaxCapacity property to less than Int32.MaxValue if your app is handling large strings that may cause it to execute in a memory-constrained environment.

具現化 StringBuilder 物件Instantiating a StringBuilder object

您具現化StringBuilder藉由呼叫其六個多載的類別建構函式下, 表中所列出的其中一個物件。You instantiate a StringBuilder object by calling one of its six overloaded class constructors, which are listed in the following table. 三個建構函式具現化StringBuilder物件,其值為空字串,但將其CapacityMaxCapacity不同值。Three of the constructors instantiate a StringBuilder object whose value is an empty string, but set its Capacity and MaxCapacity values differently. 其餘的三個建構函式定義StringBuilder具有特定的字串值和容量的物件。The remaining three constructors define a StringBuilder object that has a specific string value and capacity. 兩個的三個建構函式使用的預設最大容量Int32.MaxValue,而第三個可讓您設定的最大容量。Two of the three constructors use the default maximum capacity of Int32.MaxValue, whereas the third allows you to set the maximum capacity.

建構函式Constructor 字串值String value 容量Capacity 最大容量Maximum capacity
StringBuilder() String.Empty 1616 Int32.MaxValue
StringBuilder(Int32) String.Empty 藉由定義capacity參數Defined by the capacity parameter Int32.MaxValue
StringBuilder(Int32, Int32) String.Empty 藉由定義capacity參數Defined by the capacity parameter 藉由定義maxCapacity參數Defined by the maxCapacity parameter
StringBuilder(String) 藉由定義value參數Defined by the value parameter 16 或value16 or value. Length為準Length, whichever is greater Int32.MaxValue
StringBuilder(String, Int32) 藉由定義value參數Defined by the value parameter 藉由定義capacity參數或valueDefined by the capacity parameter or value. Length為準。Length, whichever is greater. Int32.MaxValue
StringBuilder(String, Int32, Int32, Int32) value 定義。Defined by value. Substring(startIndex, length)Substring(startIndex, length) 藉由定義capacity參數或valueDefined by the capacity parameter or value. Length為準。Length, whichever is greater. 藉由定義maxCapacity參數Defined by the maxCapacity parameter

下列範例會使用這些建構函式多載的三個具現化StringBuilder物件。The following example uses three of these constructor overloads to instantiate StringBuilder objects.

using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      string value = "An ordinary string";
      int index = value.IndexOf("An ") + 3;
      int capacity = 0xFFFF;
      
      // Instantiate a StringBuilder from a string.
      StringBuilder sb1 = new StringBuilder(value);
      ShowSBInfo(sb1); 
      
      // Instantiate a StringBuilder from string and define a capacity.  
      StringBuilder sb2 = new StringBuilder(value, capacity);   
      ShowSBInfo(sb2); 
      
      // Instantiate a StringBuilder from substring and define a capacity.  
      StringBuilder sb3 = new StringBuilder(value, index, 
                                            value.Length - index, 
                                            capacity );
      ShowSBInfo(sb3); 
   }

   public static void ShowSBInfo(StringBuilder sb)
   {
      Console.WriteLine("\nValue: {0}", sb.ToString());
      foreach (var prop in sb.GetType().GetProperties()) {
         if (prop.GetIndexParameters().Length == 0)
            Console.Write("{0}: {1:N0}    ", prop.Name, prop.GetValue(sb));
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    Value: An ordinary string
//    Capacity: 18    MaxCapacity: 2,147,483,647    Length: 18
//    
//    Value: An ordinary string
//    Capacity: 65,535    MaxCapacity: 2,147,483,647    Length: 18
//    
//    Value: ordinary string
//    Capacity: 65,535    MaxCapacity: 2,147,483,647    Length: 15
Imports System.Text

Module Example
   Public Sub Main()
      Dim value As String = "An ordinary string"
      Dim index As Integer = value.IndexOf("An ") + 3
      Dim capacity As Integer = &hFFFF
      
      ' Instantiate a StringBuilder from a string.
      Dim sb1 As New StringBuilder(value)
      ShowSBInfo(sb1) 
      
      ' Instantiate a StringBuilder from string and define a capacity.  
      Dim sb2 As New StringBuilder(value, capacity)   
      ShowSBInfo(sb2) 
      
      ' Instantiate a StringBuilder from substring and define a capacity.  
      Dim sb3 As New StringBuilder(value, index, 
                                   value.Length - index, 
                                   capacity )
      ShowSBInfo(sb3) 
   End Sub
   
   Public Sub ShowSBInfo(sb As StringBuilder)
      Console.WriteLine()
      Console.WriteLine("Value: {0}", sb.ToString())
      For Each prop In sb.GetType().GetProperties
         If prop.GetIndexParameters().Length = 0 Then
            Console.Write("{0}: {1:N0}    ", prop.Name, prop.GetValue(sb))
         End If   
      Next
      Console.WriteLine()
   End Sub
End Module
' The example displays the following output:
'    Value: An ordinary string
'    Capacity: 18    MaxCapacity: 2,147,483,647    Length: 18
'    
'    Value: An ordinary string
'    Capacity: 65,535    MaxCapacity: 2,147,483,647    Length: 18
'    
'    Value: ordinary string
'    Capacity: 65,535    MaxCapacity: 2,147,483,647    Length: 15

呼叫 StringBuilder 方法Calling StringBuilder methods

大部分的方法,修改中的字串StringBuilder執行個體傳回該相同的執行個體的參考。Most of the methods that modify the string in a StringBuilder instance return a reference to that same instance. 這可讓您呼叫StringBuilder有兩種方法:This enables you to call StringBuilder methods in two ways:

  • 您可以進行個別的方法呼叫,並忽略傳回值,如下列範例所示。You can make individual method calls and ignore the return value, as the following example does.

    using System;
    using System.Text;
    
    public class Example
    {
       public static void Main()
       {
          StringBuilder sb = new StringBuilder();
          sb.Append("This is the beginning of a sentence, ");
          sb.Replace("the beginning of ", "");
          sb.Insert(sb.ToString().IndexOf("a ") + 2, "complete ");
          sb.Replace(",", ".");
          Console.WriteLine(sb.ToString());
       }
    }
    // The example displays the following output:
    //        This is a complete sentence.
    
    Imports System.Text
    
    Module Example
       Public Sub Main()
          Dim sb As New StringBuilder()
          sb.Append("This is the beginning of a sentence, ")
          sb.Replace("the beginning of ", "")
          sb.Insert(sb.ToString().IndexOf("a ") + 2, "complete ")
          sb.Replace(",", ".")
          Console.WriteLine(sb.ToString())
       End Sub
    End Module
    ' The example displays the following output:
    '       This is a complete sentence.
    
  • 您可以在單一陳述式的一系列的方法呼叫。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.

    using System;
    using System.Text;
    
    public class Example
    {
       public static void Main()
       {
          StringBuilder sb = new StringBuilder("This is the beginning of a sentence, ");
          sb.Replace("the beginning of ", "").Insert(sb.ToString().IndexOf("a ") + 2, 
                                                     "complete ").Replace(",", ".");
          Console.WriteLine(sb.ToString());
       }
    }
    // The example displays the following output:
    //        This is a complete sentence.
    
    Imports System.Text
    
    Module Example
       Public Sub Main()
          Dim sb As New StringBuilder("This is the beginning of a sentence, ")
          sb.Replace("the beginning of ", "").Insert(sb.ToString().IndexOf("a ") + 2, _
                                                     "complete ").Replace(", ", ".")
          Console.WriteLine(sb.ToString())
       End Sub
    End Module
    ' The example displays the following output:
    '       This is a complete sentence.
    

執行 StringBuilder 作業Performing StringBuilder operations

您可以使用的方法StringBuilder類別來逐一查看、 新增、 刪除或修改中的字元StringBuilder物件。You can use the methods of the StringBuilder class to iterate, add, delete, or modify characters in a StringBuilder object.

逐一查看 StringBuilder 字元Iterating StringBuilder characters

您可以存取中的字元StringBuilder物件使用StringBuilder.Chars[Int32]屬性。You can access the characters in a StringBuilder object by using the StringBuilder.Chars[Int32] property. 在 C# 中,Chars[Int32]是索引子,就在 Visual Basic 中的預設屬性StringBuilder類別。In C#, Chars[Int32] is an indexer; in Visual Basic, it is the default property of the StringBuilder class. 這可讓您設定或使用其索引,而不需要明確參考來擷取個別字元Chars[Int32]屬性。This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the Chars[Int32] property. 中的字元StringBuilder物件開始索引為 0 (零),並繼續編製索引Length-1。Characters in a StringBuilder object begin at index 0 (zero) and continue to index Length - 1.

下列範例說明Chars[Int32]屬性。The following example illustrates the Chars[Int32] property. 它會將附加至 10 個隨機數字StringBuilder物件,然後再逐一查看每個字元。It appends ten random numbers to a StringBuilder object, and then iterates each character. 如果是字元的 Unicode 分類UnicodeCategory.DecimalDigitNumber,它表示數目減 1 (或其值為 0 會變成 9 的數字)。If the character's Unicode category is UnicodeCategory.DecimalDigitNumber, it decreases the number by 1 (or changes the number to 9 if its value is 0). 此範例會顯示的內容StringBuilder物件兩者之前和之後的個別字元的值已變更。The example displays the contents of the StringBuilder object both before and after the values of individual characters were changed.

using System;
using System.Globalization;
using System.Text;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      StringBuilder sb = new StringBuilder();
      
      // Generate 10 random numbers and store them in a StringBuilder.
      for (int ctr = 0; ctr <= 9; ctr++)
         sb.Append(rnd.Next().ToString("N5"));    

      Console.WriteLine("The original string:");
      Console.WriteLine(sb.ToString());
            
      // Decrease each number by one.
      for (int ctr = 0; ctr < sb.Length; ctr++) {
         if (Char.GetUnicodeCategory(sb[ctr]) == UnicodeCategory.DecimalDigitNumber) {
            int number = (int) Char.GetNumericValue(sb[ctr]);
            number--;
            if (number < 0) number = 9;
         
            sb[ctr] = number.ToString()[0];
         }
      }
      Console.WriteLine("\nThe new string:");
      Console.WriteLine(sb.ToString());
   }
}
// The example displays the following output:
//    The original string:
//    1,457,531,530.00000940,522,609.000001,668,113,564.000001,998,992,883.000001,792,660,834.00
//    000101,203,251.000002,051,183,075.000002,066,000,067.000001,643,701,043.000001,702,382,508
//    .00000
//    
//    The new string:
//    0,346,420,429.99999839,411,598.999990,557,002,453.999990,887,881,772.999990,681,559,723.99
//    999090,192,140.999991,940,072,964.999991,955,999,956.999990,532,690,932.999990,691,271,497
//    .99999
Imports System.Globalization
Imports System.Text

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim sb As New StringBuilder()
      
      ' Generate 10 random numbers and store them in a StringBuilder.
      For ctr As Integer = 0 To 9
         sb.Append(rnd.Next().ToString("N5"))    
      Next
      Console.WriteLine("The original string:")
      Console.WriteLine(sb.ToString())
      Console.WriteLine()
            
      ' Decrease each number by one.
      For ctr As Integer = 0 To sb.Length - 1
         If Char.GetUnicodeCategory(sb(ctr)) = UnicodeCategory.DecimalDigitNumber Then
            Dim number As Integer = CType(Char.GetNumericValue(sb(ctr)), Integer)
            number -= 1
            If number < 0 Then number = 9
         
            sb(ctr) = number.ToString()(0)
         End If
      Next
      Console.WriteLine("The new string:")
      Console.WriteLine(sb.ToString())
   End Sub
End Module
' The example displays the following output:
'    The original string:
'    1,457,531,530.00000940,522,609.000001,668,113,564.000001,998,992,883.000001,792,660,834.00
'    000101,203,251.000002,051,183,075.000002,066,000,067.000001,643,701,043.000001,702,382,508
'    .00000
'    
'    The new string:
'    0,346,420,429.99999839,411,598.999990,557,002,453.999990,887,881,772.999990,681,559,723.99
'    999090,192,140.999991,940,072,964.999991,955,999,956.999990,532,690,932.999990,691,271,497
'    .99999

在下列狀況下,搭配使用以字元為主的索引與 Chars[Int32] 屬性可能極為緩慢:Using character-based indexing with the Chars[Int32] property can be extremely slow under the following conditions:

由於每個字元的存取會行經整個連結的區塊清單來尋找要編入索引的正確緩衝區,因此會嚴重影響效能。Performance is severely impacted because each character access walks the entire linked list of chunks to find the correct buffer to index into.

注意

即使對於大型「塊狀」StringBuilder 物件,使用 Chars[Int32] 對一個或少數字元進行以索引為主的存取,也只有些許的效能影響;一般來說,這是 0(n) 作業。Even for a large "chunky" StringBuilder object, using the Chars[Int32] property for index-based access to one or a small number of characters has a negligible performance impact; typically, it is an 0(n) operation. 逐一查看 StringBuilder 物件中的字元時,就會發生顯著的效能影響,這是 O(n^2) 作業。The significant performance impact occurs when iterating the characters in the StringBuilder object, which is an O(n^2) operation.

如果在 StringBuilder 物件中使用以字元為主的索引時遇到效能問題,您可以使用下列任一因應措施:If you encounter performance issues when using character-based indexing with StringBuilder objects, you can use any of the following workarounds:

  • 藉由呼叫 ToString 方法將 StringBuilder 執行個體轉換為 String,然後存取字串中的字元。Convert the StringBuilder instance to a String by calling the ToString method, then access the characters in the string.

  • 將現有 StringBuilder 物件的內容複製到預留大小的新 StringBuilder 物件。Copy the contents of the existing StringBuilder object to a new pre-sized StringBuilder object. 因為新的 StringBuilder 物件不是塊狀,所以會改善效能。Performance improves because the new StringBuilder object is not chunky. 例如:For example:

    // sbOriginal is the existing StringBuilder object
    var sbNew = new StringBuilder(sbOriginal.ToString(), sbOriginal.Length);
    
    ' sbOriginal is the existing StringBuilder object
    Dim sbNew = New StringBuilder(sbOriginal.ToString(), sbOriginal.Length)
    
  • 藉由呼叫 StringBuilder(Int32) 建構函式,將 StringBuilder 物件的初始容量設定為大約等於其預期大小上限的值。Set the initial capacity of the StringBuilder object to a value that is approximately equal to its maximum expected size by calling the StringBuilder(Int32) constructor. 請注意,即使 StringBuilder 很少達到其最大容量,這也會配置整個記憶體區塊。Note that this allocates the entire block of memory even if the StringBuilder rarely reaches its maximum capacity.

將文字新增至的 StringBuilder 物件Adding text to a StringBuilder object

StringBuilder類別包含下列方法來擴充內容StringBuilder物件:The StringBuilder class includes the following methods for expanding the contents of a StringBuilder object:

  • Append方法會將附加的字串、 子字串、 字元陣列、 在字元陣列的一部分的單一字元重複許多次,或基本資料的字串表示法輸入以StringBuilder物件。The Append 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 StringBuilder object.

  • AppendLine方法會將行結束字元或行結束字元字串附加StringBuilder物件。The AppendLine method appends a line terminator or a string along with a line terminator to a StringBuilder object.

  • AppendFormat方法會附加複合格式字串StringBuilder物件。The AppendFormat method appends a composite format string to a 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.

  • Insert方法會將插入字串,子字串,將字串的多個重複項目中的指定位置的字元陣列、 在字元陣列的一部分或基本資料的字串表示法輸入StringBuilder物件。The Insert 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 StringBuilder object. 以零為起始的索引所定義的位置。The position is defined by a zero-based index.

下列範例會使用AppendAppendLineAppendFormat,以及Insert方法,以展開的文字StringBuilder物件。The following example uses the Append, AppendLine, AppendFormat, and Insert methods to expand the text of a StringBuilder object.

using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      // Create a StringBuilder object with no text.
      StringBuilder sb = new StringBuilder();
      // Append some text.
      sb.Append('*', 10).Append(" Adding Text to a StringBuilder Object ").Append('*', 10);
      sb.AppendLine("\n");
      sb.AppendLine("Some code points and their corresponding characters:");
      // Append some formatted text.
      for (int ctr = 50; ctr <= 60; ctr++) {
         sb.AppendFormat("{0,12:X4} {1,12}", ctr, Convert.ToChar(ctr));
         sb.AppendLine();
      }
      // Find the end of the introduction to the column.
      int pos = sb.ToString().IndexOf("characters:") + 11 + 
                Environment.NewLine.Length;
      // Insert a column header.
      sb.Insert(pos, String.Format("{2}{0,12:X4} {1,12}{2}", "Code Unit", 
                                   "Character", "\n"));      

      // Convert the StringBuilder to a string and display it.      
      Console.WriteLine(sb.ToString());      
   }
}
// The example displays the following output:
//    ********** Adding Text to a StringBuilder Object **********
//    
//    Some code points and their corresponding characters:
//    
//       Code Unit    Character
//            0032            2
//            0033            3
//            0034            4
//            0035            5
//            0036            6
//            0037            7
//            0038            8
//            0039            9
//            003A            :
//            003B            ;
//            003C            <
Imports System.Text

Module Example
   Public Sub Main()
      ' Create a StringBuilder object with no text.
      Dim sb As New StringBuilder()
      ' Append some text.
      sb.Append("*"c, 10).Append(" Adding Text to a StringBuilder Object ").Append("*"c, 10)
      sb.AppendLine()
      sb.AppendLine()
      sb.AppendLine("Some code points and their corresponding characters:")
      ' Append some formatted text.
      For ctr = 50 To 60
         sb.AppendFormat("{0,12:X4} {1,12}", ctr, Convert.ToChar(ctr))
         sb.AppendLine()
      Next
      ' Find the end of the introduction to the column.
      Dim pos As Integer = sb.ToString().IndexOf("characters:") + 11 + 
                           Environment.NewLine.Length
      ' Insert a column header.
      sb.Insert(pos, String.Format("{2}{0,12:X4} {1,12}{2}", "Code Unit", 
                                   "Character", vbCrLf))      

      ' Convert the StringBuilder to a string and display it.      
      Console.WriteLine(sb.ToString())      
   End Sub
End Module
' The example displays the following output:
'       ********** Adding Text to a StringBuilder Object **********
'       
'       Some code points and their corresponding characters:
'       
'          Code Unit    Character
'               0032            2
'               0033            3
'               0034            4
'               0035            5
'               0036            6
'               0037            7
'               0038            8
'               0039            9
'               003A            :
'               003B            ;
'               003C            <

刪除文字自 StringBuilder 物件Deleting text from a StringBuilder object

StringBuilder類別包含方法,就目前的大小縮減StringBuilder執行個體。The StringBuilder class includes methods that can reduce the size of the current StringBuilder instance. Clear方法會移除所有字元,並設定Length屬性設為零。The Clear method removes all characters and sets the Length property to zero. Remove方法會刪除指定的特定索引位置開始的字元數。The Remove method deletes a specified number of characters starting at a particular index position. 此外,您可以從結尾移除字元StringBuilder物件,藉由設定其Length屬性設為小於目前的執行個體的長度的值。In addition, you can remove characters from the end of a StringBuilder object by setting its Length property to a value that is less than the length of the current instance.

下列範例會移除部分中的文字StringBuilder物件,其產生的容量、 最大容量和長度屬性值,會顯示,然後呼叫Clear方法來移除所有字元StringBuilder物件。The following example removes some of the text from a StringBuilder object, displays its resulting capacity, maximum capacity, and length property values, and then calls the Clear method to remove all the characters from the StringBuilder object.

using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      StringBuilder sb = new StringBuilder("A StringBuilder object");
      ShowSBInfo(sb);
      // Remove "object" from the text.
      string textToRemove = "object";
      int pos = sb.ToString().IndexOf(textToRemove);
      if (pos >= 0) {
         sb.Remove(pos, textToRemove.Length);
         ShowSBInfo(sb);
      }
      // Clear the StringBuilder contents.
      sb.Clear();
      ShowSBInfo(sb);   
   }

   public static void ShowSBInfo(StringBuilder sb)
   {
      Console.WriteLine("\nValue: {0}", sb.ToString());
      foreach (var prop in sb.GetType().GetProperties()) {
         if (prop.GetIndexParameters().Length == 0)
            Console.Write("{0}: {1:N0}    ", prop.Name, prop.GetValue(sb));
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    Value: A StringBuilder object
//    Capacity: 22    MaxCapacity: 2,147,483,647    Length: 22
//    
//    Value: A StringBuilder
//    Capacity: 22    MaxCapacity: 2,147,483,647    Length: 16
//    
//    Value:
//    Capacity: 22    MaxCapacity: 2,147,483,647    Length: 0
Imports System.Text

Module Example
   Public Sub Main()
      Dim sb As New StringBuilder("A StringBuilder object")
      ShowSBInfo(sb)
      ' Remove "object" from the text.
      Dim textToRemove As String = "object"
      Dim pos As Integer = sb.ToString().IndexOf(textToRemove)
      If pos >= 0
         sb.Remove(pos, textToRemove.Length)
         ShowSBInfo(sb)
      End If
      ' Clear the StringBuilder contents.
      sb.Clear()
      ShowSBInfo(sb)   
   End Sub

   Public Sub ShowSBInfo(sb As StringBuilder)
      Console.WriteLine()
      Console.WriteLine("Value: {0}", sb.ToString())
      For Each prop In sb.GetType().GetProperties
         If prop.GetIndexParameters().Length = 0 Then
            Console.Write("{0}: {1:N0}    ", prop.Name, prop.GetValue(sb))
         End If   
      Next
      Console.WriteLine()
   End Sub
End Module
' The example displays the following output:
'    Value: A StringBuilder object
'    Capacity: 22    MaxCapacity: 2,147,483,647    Length: 22
'    
'    Value: A StringBuilder
'    Capacity: 22    MaxCapacity: 2,147,483,647    Length: 16
'    
'    Value:
'    Capacity: 22    MaxCapacity: 2,147,483,647    Length: 0

修改 StringBuilder 物件中的文字Modifying the text in a StringBuilder object

StringBuilder.Replace方法會取代所有出現的字元或字串,以在整個StringBuilder物件或在特定的字元範圍。The StringBuilder.Replace method replaces all occurrences of a character or a string in the entire StringBuilder object or in a particular character range. 下列範例會使用Replace方法以問號 (?) 取代所有的驚嘆號 (!),在StringBuilder物件。The following example uses the Replace method to replace all exclamation points (!) with question marks (?) in the StringBuilder object.

using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
      MyStringBuilder.Replace('!', '?');
      Console.WriteLine(MyStringBuilder);
   }
}
// The example displays the following output:
//       Hello World?
Imports System.Text

Module Example
   Public Sub Main()
      Dim MyStringBuilder As New StringBuilder("Hello World!")
      MyStringBuilder.Replace("!"c, "?"c)
      Console.WriteLine(MyStringBuilder)
   End Sub
End Module
' The example displays the following output:
'       Hello World?

StringBuilder 物件中搜尋文字Searching the text in a StringBuilder object

StringBuilder類別不包含方法類似於String.ContainsString.IndexOf,以及String.StartsWith所提供的方法String類別,可讓您搜尋特定字元或子字串的物件。The StringBuilder class does not include methods similar to the String.Contains, String.IndexOf, and String.StartsWith methods provided by the String class, which allow you to search the object for a particular character or a substring. 判斷是否存在,或開始之子字串的字元位置,需要您搜尋String使用字串搜尋方法或規則運算式方法的值。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.

技術Technique 專業人員Pros 缺點Cons
搜尋字串值,再將它們加入至StringBuilder物件。Search string values before adding them to the StringBuilder object. 適用於判斷子字串是否存在。Useful for determining whether a substring exists. 子字串的索引位置都很重要時,無法使用。Cannot be used when the index position of a substring is important.
呼叫ToString並搜尋傳回String物件。Call ToString and search the returned String object. 簡單易用,如果您將指派到的所有文字StringBuilder物件,然後再開始進行修改。Easy to use if you assign all the text to a StringBuilder object, and then begin to modify it. 重複地呼叫麻煩ToString如果所有的文字已加入之前,您必須先修改StringBuilder物件。Cumbersome to repeatedly call ToString if you must make modifications before all text is added to the StringBuilder object.

從結尾時,您必須記得StringBuilder物件的文字,如果您這樣做的變更。You must remember to work from the end of the StringBuilder object's text if you're making changes.
使用Chars[Int32]循序搜尋的字元範圍的屬性。Use the Chars[Int32] 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.

在核心重複的方法呼叫透過非常大型的物件的效能非常低落的結果。Results in very poor performance for objects that have grown very large through repeated method calls.
轉換StringBuilder物件至String物件,並在執行修改String物件。Convert the StringBuilder object to a String object, and perform modifications on the String object. 如果所做的修改數目少很有用。Useful if the number of modifications is small. 否定的效能優勢StringBuilder類別所做的修改數目很大。Negates the performance benefit of the StringBuilder class if the number of modifications is large.

讓我們來檢查詳細說明這些技術。Let's examine these techniques in greater detail.

  • 如果搜尋的目標是要判斷是否為特定的子字串存在 (亦即,如果您不感興趣的子字串的位置),您可以搜尋字串,然後再將它們儲存在StringBuilder物件。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 StringBuilder object. 下列範例提供一個可能的實作。The following example provides one possible implementation. 它會定義StringBuilderFinder類別的建構函式的參考會傳遞給StringBuilder物件和要在字串中找到的子字串。It defines a StringBuilderFinder class whose constructor is passed a reference to a StringBuilder object and the substring to find in the string. 此範例在此情況下,會嘗試判斷是否已錄製的溫度華氏或攝氏溫度,以及將適當的簡介文字的開頭加入StringBuilder物件。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 StringBuilder object. 亂數產生器用來選取陣列,其中包含為攝氏或華氏的資料。A random number generator is used to select an array that contains data in either degrees Celsius or degrees Fahrenheit.

    using System;
    using System.Text;
    
    public class Example
    {
       public static void Main()
       {
          Random rnd = new Random();
          string[] tempF = { "47.6F", "51.3F", "49.5F", "62.3F" };
          string[] tempC = { "21.2C", "16.1C", "23.5C", "22.9C" };
          string[][] temps = { tempF, tempC }; 
    
          StringBuilder sb = new StringBuilder();
          var f = new StringBuilderFinder(sb, "F");
          var baseDate = new DateTime(2013, 5, 1); 
          String[] temperatures = temps[rnd.Next(2)];
          bool isFahrenheit = false;
          foreach (var temperature in temperatures) {
             if (isFahrenheit)
                sb.AppendFormat("{0:d}: {1}\n", baseDate, temperature);
             else
                isFahrenheit = f.SearchAndAppend(String.Format("{0:d}: {1}\n", 
                                                 baseDate, temperature));
             baseDate = baseDate.AddDays(1);
          }            
          if (isFahrenheit) {
             sb.Insert(0, "Average Daily Temperature in Degrees Fahrenheit");
             sb.Insert(47, "\n\n");
          }
          else {
             sb.Insert(0, "Average Daily Temperature in Degrees Celsius");
             sb.Insert(44, "\n\n");
          }   
          Console.WriteLine(sb.ToString());
       }
    }
    
    public class StringBuilderFinder
    {
       private StringBuilder sb;
       private String text;
       
       public StringBuilderFinder(StringBuilder sb, String textToFind)
       {
          this.sb = sb;
          this.text = textToFind;
       }
       
       public bool SearchAndAppend(String stringToSearch)
       {
          sb.Append(stringToSearch);
          return stringToSearch.Contains(text);
       }
    }
    // The example displays output similar to the following:
    //    Average Daily Temperature in Degrees Celsius
    //    
    //    5/1/2013: 21.2C
    //    5/2/2013: 16.1C
    //    5/3/2013: 23.5C
    //    5/4/2013: 22.9C
    
    Imports System.Text
    
    Module Example
       Public Sub Main()
          Dim rnd As New Random()
          Dim tempF() As String = { "47.6F", "51.3F", "49.5F", "62.3F" }
          Dim tempC() As String = { "21.2C", "16.1C", "23.5C", "22.9C" }
          Dim temps()() As String = { tempF, tempC } 
    
          Dim sb As StringBuilder = New StringBuilder()
          Dim f As New StringBuilderFinder(sb, "F")
          Dim baseDate As New DateTime(2013, 5, 1) 
          Dim temperatures() As String = temps(rnd.Next(2))
          Dim isFahrenheit As Boolean = False
          For Each temperature In temperatures
             If isFahrenheit Then
                sb.AppendFormat("{0:d}: {1}{2}", baseDate, temperature, vbCrLf)
             Else
                isFahrenheit = f.SearchAndAppend(String.Format("{0:d}: {1}{2}", 
                                                 baseDate, temperature, vbCrLf))
             End If
             baseDate = baseDate.AddDays(1)
          Next            
          If isFahrenheit Then
             sb.Insert(0, "Average Daily Temperature in Degrees Fahrenheit")
             sb.Insert(47, vbCrLf + vbCrLf)
          Else
             sb.Insert(0, "Average Daily Temperature in Degrees Celsius")
             sb.Insert(44, vbCrLf + vbCrLf)
          End If   
          Console.WriteLine(sb.ToString())
       End Sub
    End Module
    
    Public Class StringBuilderFinder
       Private sb As StringBuilder
       Private text As String
       
       Public Sub New(sb As StringBuilder, textToFind As String)
          Me.sb = sb
          text = textToFind
       End Sub
       
       Public Function SearchAndAppend(stringToSearch As String) As Boolean
          sb.Append(stringToSearch)
          Return stringToSearch.Contains(text)
       End Function
    End Class
    ' The example displays output similar to the following:
    '    Average Daily Temperature in Degrees Celsius
    '    
    '    5/1/2013: 21.2C
    '    5/2/2013: 16.1C
    '    5/3/2013: 23.5C
    '    5/4/2013: 22.9C
    
  • 呼叫StringBuilder.ToString方法,將轉換StringBuilder物件到String物件。Call the StringBuilder.ToString method to convert the StringBuilder object to a String object. 您可以使用下列方法來搜尋字串String.LastIndexOf或是String.StartsWith,或者您可以使用規則運算式和Regex類別搜尋模式。You can search the string by using methods such as String.LastIndexOf or String.StartsWith, or you can use regular expressions and the Regex class to search for patterns. 因為這兩StringBuilderString物件會使用 utf-16 編碼方式儲存的子字串的字元的索引位置的字元和規則運算式相符項目是在這兩個物件相同。Because both 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. 這可讓您使用StringBuilder方法,以變更該文字位於相同位置String物件。This enables you to use StringBuilder methods to make changes at the same position at which that text is found in the String object.

    注意

    如果您採用這種方法,您都能從結尾StringBuilder物件,其開始,讓您不必重複轉換StringBuilder為字串的物件。If you adopt this approach, you should work from the end of the StringBuilder object to its beginning so that you don't have to repeatedly convert the StringBuilder object to a string.

    下列範例將示範這個方法。The following example illustrates this approach. 它會儲存每個字母英文字母,在四個相符項目StringBuilder物件。It stores four occurrences of each letter of the English alphabet in a StringBuilder object. 然後將轉換的文字String物件,並使用規則運算式來識別每個四個字元序列的開始位置。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.

    using System;
    using System.Text;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          // Create a StringBuilder object with 4 successive occurrences 
          // of each character in the English alphabet. 
          StringBuilder sb = new StringBuilder();
          for (ushort ctr = (ushort)'a'; ctr <= (ushort) 'z'; ctr++)
             sb.Append(Convert.ToChar(ctr), 4);
          
          // Create a parallel string object.
          String sbString = sb.ToString();
          // Determine where each new character sequence begins.
          String pattern = @"(\w)\1+";
          MatchCollection matches = Regex.Matches(sbString, pattern);
    
          // Uppercase the first occurrence of the sequence, and separate it
          // from the previous sequence by an underscore character.
          for (int ctr = matches.Count - 1; ctr >= 0; ctr--) { 
             Match m = matches[ctr];
             sb[m.Index] = Char.ToUpper(sb[m.Index]);
             if (m.Index > 0) sb.Insert(m.Index, "_");
          }
          // Display the resulting string.
          sbString = sb.ToString();
          int line = 0;
          do {
             int nChars = line * 80 + 79 <= sbString.Length ? 
                                 80 : sbString.Length - line * 80;
             Console.WriteLine(sbString.Substring(line * 80, nChars));
             line++;
          } while (line * 80 < sbString.Length);
       }
    }
    // The example displays the following output:
    //    Aaaa_Bbbb_Cccc_Dddd_Eeee_Ffff_Gggg_Hhhh_Iiii_Jjjj_Kkkk_Llll_Mmmm_Nnnn_Oooo_Pppp_
    //    Qqqq_Rrrr_Ssss_Tttt_Uuuu_Vvvv_Wwww_Xxxx_Yyyy_Zzzz
    
    Imports System.Text
    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          ' Create a StringBuilder object with 4 successive occurrences 
          ' of each character in the English alphabet. 
          Dim sb As New StringBuilder()
          For ctr As UShort = AscW("a") To Ascw("z")
             sb.Append(ChrW(ctr), 4)
          Next    
          ' Create a parallel string object.
          Dim sbString As String = sb.ToString()
          ' Determine where each new character sequence begins.
          Dim pattern As String = "(\w)\1+"
          Dim matches As MatchCollection = Regex.Matches(sbString, pattern)
    
          ' Uppercase the first occurrence of the sequence, and separate it
          ' from the previous sequence by an underscore character.
          For ctr As Integer = matches.Count - 1 To 0 Step -1 
             Dim m As Match = matches(ctr)
             sb.Chars(m.Index) = Char.ToUpper(sb.Chars(m.index))
             If m.Index > 0 Then sb.Insert(m.Index, "_")
          Next
          ' Display the resulting string.
          sbString = sb.ToString()
          Dim line As Integer = 0
          Do
             Dim nChars As Integer = If(line * 80 + 79 <= sbString.Length, 
                                        80, sbString.Length - line * 80)
             Console.WriteLine(sbString.Substring(line * 80, nChars))
             line += 1
          Loop While line * 80 < sbString.Length
       End Sub
    End Module
    ' The example displays the following output:
    '    Aaaa_Bbbb_Cccc_Dddd_Eeee_Ffff_Gggg_Hhhh_Iiii_Jjjj_Kkkk_Llll_Mmmm_Nnnn_Oooo_Pppp_
    '    Qqqq_Rrrr_Ssss_Tttt_Uuuu_Vvvv_Wwww_Xxxx_Yyyy_Zzzz
    
  • 使用StringBuilder.Chars[Int32]屬性,來循序搜尋中的字元範圍StringBuilder物件。Use the StringBuilder.Chars[Int32] property to sequentially search a range of characters in a 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. 如需效能含意,逐字元的索引為基礎的存取非常大型的區塊StringBuilder物件,請參閱文件StringBuilder.Chars[Int32]屬性。For the performance implications of character-by-character index-based access for very large, chunked StringBuilder objects, see the documentation for the StringBuilder.Chars[Int32] property.

    下列範例是前一個範例相同的功能,但在實作不同。The following example is identical in functionality to the previous example but differs in implementation. 它會使用Chars[Int32]屬性,以偵測何時變更的字元值,該位置插入底線,並將新序列的第一個字元轉換成大寫。It uses the Chars[Int32] 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.

    using System;
    using System.Text;
    
    public class Example
    {
       public static void Main()
       {
          // Create a StringBuilder object with 4 successive occurrences 
          // of each character in the English alphabet. 
          StringBuilder sb = new StringBuilder();
          for (ushort ctr = (ushort) 'a'; ctr <= (ushort) 'z'; ctr++)
             sb.Append(Convert.ToChar(ctr), 4);
    
          // Iterate the text to determine when a new character sequence occurs.
          int position = 0;
          Char current = '\u0000';
          do {
             if (sb[position] != current) {
                current = sb[position];
                sb[position] = Char.ToUpper(sb[position]);
                if (position > 0) 
                   sb.Insert(position, "_");
                position += 2;
             }
             else {
                position++;
             }      
          } while (position <= sb.Length - 1);
          // Display the resulting string.
          String sbString = sb.ToString();
          int line = 0;
          do {
             int nChars = line * 80 + 79 <= sbString.Length ? 
                                 80 : sbString.Length - line * 80;
             Console.WriteLine(sbString.Substring(line * 80, nChars));
             line++;
          } while (line * 80 < sbString.Length);
       }
    }
    // The example displays the following output:
    //    Aaaa_Bbbb_Cccc_Dddd_Eeee_Ffff_Gggg_Hhhh_Iiii_Jjjj_Kkkk_Llll_Mmmm_Nnnn_Oooo_Pppp_
    //    Qqqq_Rrrr_Ssss_Tttt_Uuuu_Vvvv_Wwww_Xxxx_Yyyy_Zzzz
    
    Imports System.Text
    
    Module Example
       Public Sub Main()
          ' Create a StringBuilder object with 4 successive occurrences 
          ' of each character in the English alphabet. 
          Dim sb As New StringBuilder()
          For ctr As UShort = AscW("a") To Ascw("z")
             sb.Append(ChrW(ctr), 4)
          Next    
          ' Iterate the text to determine when a new character sequence occurs.
          Dim position As Integer = 0
          Dim current As Char = ChrW(0)
          Do
             If sb(position) <> current Then
                current = sb(position)
                sb(position) = Char.ToUpper(sb(position))
                If position > 0 Then sb.Insert(position, "_")
                position += 2
             Else
                position += 1
             End If      
          Loop While position <= sb.Length - 1
          ' Display the resulting string.
          Dim sbString As String = sb.ToString()
          Dim line As Integer = 0
          Do
             Dim nChars As Integer = If(line * 80 + 79 <= sbString.Length, 
                                        80, sbString.Length - line * 80)
             Console.WriteLine(sbString.Substring(line * 80, nChars))
             line += 1
          Loop While line * 80 < sbString.Length
       End Sub
    End Module
    ' The example displays the following output:
    '    Aaaa_Bbbb_Cccc_Dddd_Eeee_Ffff_Gggg_Hhhh_Iiii_Jjjj_Kkkk_Llll_Mmmm_Nnnn_Oooo_Pppp_
    '    Qqqq_Rrrr_Ssss_Tttt_Uuuu_Vvvv_Wwww_Xxxx_Yyyy_Zzzz
    
  • 存放區中的所有未修改的文字StringBuilder物件,請呼叫StringBuilder.ToString方法,將轉換StringBuilder物件String物件,並對所做的修改String物件。Store all the unmodified text in the StringBuilder object, call the StringBuilder.ToString method to convert the StringBuilder object to a String object, and perform the modifications on the String object. 您可以使用這種方法,如果您有只有少數修改;否則,請使用不可變的字串的成本可能不利於效能使用StringBuilder物件。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 StringBuilder object.

    下列範例與上述的兩個範例相同的功能,但在實作兩者不同。The following example is identical in functionality to the previous two examples but differs in implementation. 它會建立StringBuilder物件,將它轉換成String物件,並接著會使用規則運算式字串上執行所有剩餘的修改。It creates a StringBuilder object, converts it to a String object, and then uses a regular expression to perform all remaining modifications on the string. Regex.Replace(String, String, MatchEvaluator)方法使用 lambda 運算式,以在每個相符項目上執行取代。The Regex.Replace(String, String, MatchEvaluator) method uses a lambda expression to perform the replacement on each match.

    using System;
    using System.Text;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          // Create a StringBuilder object with 4 successive occurrences 
          // of each character in the English alphabet. 
          StringBuilder sb = new StringBuilder();
          for (ushort ctr = (ushort)'a'; ctr <= (ushort) 'z'; ctr++)
             sb.Append(Convert.ToChar(ctr), 4);
         
          // Convert it to a string.
          String sbString = sb.ToString();
    
          // Use a regex to uppercase the first occurrence of the sequence, 
          // and separate it from the previous sequence by an underscore.
          string pattern = @"(\w)(\1+)";
          sbString = Regex.Replace(sbString, pattern, 
                                   m => (m.Index > 0 ? "_" : "") + 
                                   m.Groups[1].Value.ToUpper() + 
                                   m.Groups[2].Value);
    
          // Display the resulting string.
          int line = 0;
          do {
             int nChars = line * 80 + 79 <= sbString.Length ? 
                                 80 : sbString.Length - line * 80;
             Console.WriteLine(sbString.Substring(line * 80, nChars));
             line++;
          } while (line * 80 < sbString.Length);
       }
    }
    // The example displays the following output:
    //    Aaaa_Bbbb_Cccc_Dddd_Eeee_Ffff_Gggg_Hhhh_Iiii_Jjjj_Kkkk_Llll_Mmmm_Nnnn_Oooo_Pppp_
    //    Qqqq_Rrrr_Ssss_Tttt_Uuuu_Vvvv_Wwww_Xxxx_Yyyy_Zzzz
    
    Imports System.Text
    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          ' Create a StringBuilder object with 4 successive occurrences 
          ' of each character in the English alphabet. 
          Dim sb As New StringBuilder()
          For ctr As UShort = AscW("a") To Ascw("z")
             sb.Append(ChrW(ctr), 4)
          Next    
          ' Convert it to a string.
          Dim sbString As String = sb.ToString()
    
          ' Use a regex to uppercase the first occurrence of the sequence, 
          ' and separate it from the previous sequence by an underscore.
          Dim pattern As String = "(\w)(\1+)"
          sbString = Regex.Replace(sbString, pattern, 
                                   Function(m) If(m.Index > 0,"_","") + 
                                               m.Groups(1).Value.ToUpper + 
                                               m.Groups(2).Value)
    
          ' Display the resulting string.
          Dim line As Integer = 0
          Do
             Dim nChars As Integer = If(line * 80 + 79 <= sbString.Length, 
                                        80, sbString.Length - line * 80)
             Console.WriteLine(sbString.Substring(line * 80, nChars))
             line += 1
          Loop While line * 80 < sbString.Length
       End Sub
    End Module
    ' The example displays the following output:
    '    Aaaa_Bbbb_Cccc_Dddd_Eeee_Ffff_Gggg_Hhhh_Iiii_Jjjj_Kkkk_Llll_Mmmm_Nnnn_Oooo_Pppp_
    '    Qqqq_Rrrr_Ssss_Tttt_Uuuu_Vvvv_Wwww_Xxxx_Yyyy_Zzzz
    

將 StringBuilder 物件轉換為字串Converting the StringBuilder object to a string

您必須先將 StringBuilder 物件轉換成 String 物件,才能將 StringBuilder 物件所代表的字串傳遞給具有 String 參數的方法,或在使用者介面中加以顯示。You must convert the StringBuilder object to a String object before you can pass the string represented by the StringBuilder object to a method that has a String parameter or display it in the user interface. 您可以執行這項轉換藉由呼叫StringBuilder.ToString方法。You perform this conversion by calling the StringBuilder.ToString method. 如需圖例,請參閱上述的範例中,呼叫ToString方法,將轉換StringBuilder物件的字串,使它可以傳遞至規則運算式方法。For an illustration, see the previous example, which calls the ToString method to convert a StringBuilder object to a string so that it can be passed to a regular expression method.

給呼叫者的注意事項

在.NET Core 和.NET Framework 4.0 和更新版本中,當您具現化StringBuilder藉由呼叫物件StringBuilder(Int32, Int32)建構函式,長度和容量StringBuilder執行個體可以成長的值超過其MaxCapacity屬性。In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. 這可能特別是當您呼叫Append(String)AppendFormat(String, Object)附加小字串的方法。This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.

建構函式

StringBuilder() StringBuilder() StringBuilder() StringBuilder()

初始化 StringBuilder 類別的新執行個體。Initializes a new instance of the StringBuilder class.

StringBuilder(Int32) StringBuilder(Int32) StringBuilder(Int32) StringBuilder(Int32)

使用指定的容量來初始化 StringBuilder 類別的新執行個體。Initializes a new instance of the StringBuilder class using the specified capacity.

StringBuilder(Int32, Int32) StringBuilder(Int32, Int32) StringBuilder(Int32, Int32) StringBuilder(Int32, Int32)

初始化 StringBuilder 類別的新執行個體,將從指定的容量開始並且可以增加至指定的最大值。Initializes a new instance of the StringBuilder class that starts with a specified capacity and can grow to a specified maximum.

StringBuilder(String) StringBuilder(String) StringBuilder(String) StringBuilder(String)

以指定的字串初始化 StringBuilder 類別的新執行個體。Initializes a new instance of the StringBuilder class using the specified string.

StringBuilder(String, Int32) StringBuilder(String, Int32) StringBuilder(String, Int32) StringBuilder(String, Int32)

使用指定的字串和容量,來初始化 StringBuilder 類別的新執行個體。Initializes a new instance of the StringBuilder class using the specified string and capacity.

StringBuilder(String, Int32, Int32, Int32) StringBuilder(String, Int32, Int32, Int32) StringBuilder(String, Int32, Int32, Int32) StringBuilder(String, Int32, Int32, Int32)

以指定的子字串和容量初始化 StringBuilder 類別的新執行個體。Initializes a new instance of the StringBuilder class from the specified substring and capacity.

屬性

Capacity Capacity Capacity Capacity

取得或設定由目前執行個體配置的記憶體可以包含的最大字元數。Gets or sets the maximum number of characters that can be contained in the memory allocated by the current instance.

Chars[Int32] Chars[Int32] Chars[Int32] Chars[Int32]

取得或設定這個執行個體中指定字元位置的字元。Gets or sets the character at the specified character position in this instance.

Length Length Length Length

取得或設定目前 StringBuilder 物件的長度。Gets or sets the length of the current StringBuilder object.

MaxCapacity MaxCapacity MaxCapacity MaxCapacity

取得這個執行個體的最大容量。Gets the maximum capacity of this instance.

方法

Append(Boolean) Append(Boolean) Append(Boolean) Append(Boolean)

將指定的布林 (Boolean) 值之字串表示附加至這個執行個體。Appends the string representation of a specified Boolean value to this instance.

Append(Byte) Append(Byte) Append(Byte) Append(Byte)

將指定的 8 位元不帶正負號的整數之字串表示附加至這個執行個體。Appends the string representation of a specified 8-bit unsigned integer to this instance.

Append(Char) Append(Char) Append(Char) Append(Char)

將指定 Char 物件的字串表示附加至這個執行個體。Appends the string representation of a specified Char object to this instance.

Append(Char*, Int32) Append(Char*, Int32) Append(Char*, Int32) Append(Char*, Int32)

將指定位址開頭的 Unicode 字元陣列附加至這個執行個體。Appends an array of Unicode characters starting at a specified address to this instance.

Append(Char, Int32) Append(Char, Int32) Append(Char, Int32) Append(Char, Int32)

將 Unicode 字元其字串表示的指定複本數附加至這個執行個體。Appends a specified number of copies of the string representation of a Unicode character to this instance.

Append(Char[]) Append(Char[]) Append(Char[]) Append(Char[])

將指定陣列中的 Unicode 字元的字串表示附加至這個執行個體。Appends the string representation of the Unicode characters in a specified array to this instance.

Append(Char[], Int32, Int32) Append(Char[], Int32, Int32) Append(Char[], Int32, Int32) Append(Char[], Int32, Int32)

將 Unicode 字元之指定子陣列的字串表示附加至這個執行個體。Appends the string representation of a specified subarray of Unicode characters to this instance.

Append(Decimal) Append(Decimal) Append(Decimal) Append(Decimal)

將指定的小數位數之字串表示附加至這個執行個體。Appends the string representation of a specified decimal number to this instance.

Append(Double) Append(Double) Append(Double) Append(Double)

將指定的雙精度浮點數之字串表示附加至這個執行個體。Appends the string representation of a specified double-precision floating-point number to this instance.

Append(Int16) Append(Int16) Append(Int16) Append(Int16)

將指定的 16 位元帶正負號的整數之字串表示附加至這個執行個體。Appends the string representation of a specified 16-bit signed integer to this instance.

Append(Int32) Append(Int32) Append(Int32) Append(Int32)

將指定的 32 位元帶正負號的整數之字串表示附加至這個執行個體。Appends the string representation of a specified 32-bit signed integer to this instance.

Append(Int64) Append(Int64) Append(Int64) Append(Int64)

將指定的 64 位元帶正負號的整數之字串表示附加至這個執行個體。Appends the string representation of a specified 64-bit signed integer to this instance.

Append(Object) Append(Object) Append(Object) Append(Object)

將指定物件的字串表示附加至這個執行個體。Appends the string representation of a specified object to this instance.

Append(ReadOnlyMemory<Char>) Append(ReadOnlyMemory<Char>) Append(ReadOnlyMemory<Char>) Append(ReadOnlyMemory<Char>)
Append(ReadOnlySpan<Char>) Append(ReadOnlySpan<Char>) Append(ReadOnlySpan<Char>) Append(ReadOnlySpan<Char>)
Append(SByte) Append(SByte) Append(SByte) Append(SByte)

將指定的 8 位元帶正負號的整數之字串表示附加至這個執行個體。Appends the string representation of a specified 8-bit signed integer to this instance.

Append(Single) Append(Single) Append(Single) Append(Single)

將指定的單精確度浮點數之字串表示附加至這個執行個體。Appends the string representation of a specified single-precision floating-point number to this instance.

Append(String) Append(String) Append(String) Append(String)

將指定字串的複本附加至這個執行個體。Appends a copy of the specified string to this instance.

Append(String, Int32, Int32) Append(String, Int32, Int32) Append(String, Int32, Int32) Append(String, Int32, Int32)

將指定子字串的複本附加至這個執行個體。Appends a copy of a specified substring to this instance.

Append(StringBuilder) Append(StringBuilder) Append(StringBuilder) Append(StringBuilder)
Append(StringBuilder, Int32, Int32) Append(StringBuilder, Int32, Int32) Append(StringBuilder, Int32, Int32) Append(StringBuilder, Int32, Int32)
Append(UInt16) Append(UInt16) Append(UInt16) Append(UInt16)

將指定的 16 位元不帶正負號的整數之字串表示附加至這個執行個體。Appends the string representation of a specified 16-bit unsigned integer to this instance.

Append(UInt32) Append(UInt32) Append(UInt32) Append(UInt32)

將指定的 32 位元不帶正負號的整數之字串表示附加至這個執行個體。Appends the string representation of a specified 32-bit unsigned integer to this instance.

Append(UInt64) Append(UInt64) Append(UInt64) Append(UInt64)

將指定的 64 位元不帶正負號的整數之字串表示附加至這個執行個體。Appends the string representation of a specified 64-bit unsigned integer to this instance.

AppendFormat(IFormatProvider, String, Object) AppendFormat(IFormatProvider, String, Object) AppendFormat(IFormatProvider, String, Object) AppendFormat(IFormatProvider, String, 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 single argument using a specified format provider.

AppendFormat(IFormatProvider, String, Object, Object) AppendFormat(IFormatProvider, String, Object, Object) AppendFormat(IFormatProvider, String, Object, Object) AppendFormat(IFormatProvider, String, Object, 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 either of two arguments using a specified format provider.

AppendFormat(IFormatProvider, String, Object, Object, Object) AppendFormat(IFormatProvider, String, Object, Object, Object) AppendFormat(IFormatProvider, String, Object, Object, Object) AppendFormat(IFormatProvider, String, Object, Object, 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 either of three arguments using a specified format provider.

AppendFormat(IFormatProvider, String, Object[]) AppendFormat(IFormatProvider, String, Object[]) AppendFormat(IFormatProvider, String, Object[]) AppendFormat(IFormatProvider, String, 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.

AppendFormat(String, Object) AppendFormat(String, Object) AppendFormat(String, Object) AppendFormat(String, 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 single argument.

AppendFormat(String, Object, Object) AppendFormat(String, Object, Object) AppendFormat(String, Object, Object) AppendFormat(String, Object, 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 either of two arguments.

AppendFormat(String, Object, Object, Object) AppendFormat(String, Object, Object, Object) AppendFormat(String, Object, Object, Object) AppendFormat(String, Object, Object, 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 either of three arguments.

AppendFormat(String, Object[]) AppendFormat(String, Object[]) AppendFormat(String, Object[]) AppendFormat(String, 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.

AppendJoin(Char, Object[]) AppendJoin(Char, Object[]) AppendJoin(Char, Object[]) AppendJoin(Char, Object[])
AppendJoin(Char, String[]) AppendJoin(Char, String[]) AppendJoin(Char, String[]) AppendJoin(Char, String[])
AppendJoin(String, Object[]) AppendJoin(String, Object[]) AppendJoin(String, Object[]) AppendJoin(String, Object[])
AppendJoin(String, String[]) AppendJoin(String, String[]) AppendJoin(String, String[]) AppendJoin(String, String[])
AppendJoin<T>(Char, IEnumerable<T>) AppendJoin<T>(Char, IEnumerable<T>) AppendJoin<T>(Char, IEnumerable<T>) AppendJoin<T>(Char, IEnumerable<T>)
AppendJoin<T>(String, IEnumerable<T>) AppendJoin<T>(String, IEnumerable<T>) AppendJoin<T>(String, IEnumerable<T>) AppendJoin<T>(String, IEnumerable<T>)
AppendLine() AppendLine() AppendLine() AppendLine()

將預設行結束字元附加至目前 StringBuilder 物件的尾端。Appends the default line terminator to the end of the current StringBuilder object.

AppendLine(String) AppendLine(String) AppendLine(String) AppendLine(String)

將後面接著預設行結束字元的指定字串複本附加至目前的 StringBuilder 物件結尾。Appends a copy of the specified string followed by the default line terminator to the end of the current StringBuilder object.

Clear() Clear() Clear() Clear()

從目前的 StringBuilder 執行個體移除所有字元。Removes all characters from the current StringBuilder instance.

CopyTo(Int32, Char[], Int32, Int32) CopyTo(Int32, Char[], Int32, Int32) CopyTo(Int32, Char[], Int32, Int32) CopyTo(Int32, Char[], Int32, Int32)

將此執行個體指定區段中的字元複製到目的端 Char 陣列的指定區段。Copies the characters from a specified segment of this instance to a specified segment of a destination Char array.

CopyTo(Int32, Span<Char>, Int32) CopyTo(Int32, Span<Char>, Int32) CopyTo(Int32, Span<Char>, Int32) CopyTo(Int32, Span<Char>, Int32)
EnsureCapacity(Int32) EnsureCapacity(Int32) EnsureCapacity(Int32) EnsureCapacity(Int32)

請確定這個 StringBuilder 執行個體的容量至少是某一指定的值。Ensures that the capacity of this instance of StringBuilder is at least the specified value.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Equals(ReadOnlySpan<Char>) Equals(ReadOnlySpan<Char>) Equals(ReadOnlySpan<Char>) Equals(ReadOnlySpan<Char>)

傳回值,指出此執行個體中的字元是否等於指定唯讀字元範圍的字元。Returns a value indicating whether the characters in this instance are equal to the characters in a specified read-only character span.

Equals(StringBuilder) Equals(StringBuilder) Equals(StringBuilder) Equals(StringBuilder)

傳回值,指出這個執行個體 (Instance) 是否和指定的物件相等。Returns a value indicating whether this instance is equal to a specified object.

GetChunks() GetChunks() GetChunks() GetChunks()
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
Insert(Int32, Boolean) Insert(Int32, Boolean) Insert(Int32, Boolean) Insert(Int32, Boolean)

在指定的字元位置上將 Boolean 值的字串表示插入這個執行個體。Inserts the string representation of a Boolean value into this instance at the specified character position.

Insert(Int32, Byte) Insert(Int32, Byte) Insert(Int32, Byte) Insert(Int32, Byte)

在指定的字元位置上將指定的 8 位元不帶正負號的整數之字串表示插入這個執行個體。Inserts the string representation of a specified 8-bit unsigned integer into this instance at the specified character position.

Insert(Int32, Char) Insert(Int32, Char) Insert(Int32, Char) Insert(Int32, Char)

在指定的字元位置上將指定的 Unicode 字元之字串表示插入這個執行個體。Inserts the string representation of a specified Unicode character into this instance at the specified character position.

Insert(Int32, Char[]) Insert(Int32, Char[]) Insert(Int32, Char[]) Insert(Int32, Char[])

在指定的字元位置上將指定的 Unicode 字元陣列之字串表示插入這個執行個體。Inserts the string representation of a specified array of Unicode characters into this instance at the specified character position.

Insert(Int32, Char[], Int32, Int32) Insert(Int32, Char[], Int32, Int32) Insert(Int32, Char[], Int32, Int32) Insert(Int32, Char[], Int32, Int32)

在指定的字元位置上將 Unicode 字元之指定子陣列的字串表示插入這個執行個體。Inserts the string representation of a specified subarray of Unicode characters into this instance at the specified character position.

Insert(Int32, Decimal) Insert(Int32, Decimal) Insert(Int32, Decimal) Insert(Int32, Decimal)

在指定的字元位置上將小數位數的字串表示插入這個執行個體。Inserts the string representation of a decimal number into this instance at the specified character position.

Insert(Int32, Double) Insert(Int32, Double) Insert(Int32, Double) Insert(Int32, Double)

在指定的字元位置上將雙精度浮點數的字串表示插入這個執行個體。Inserts the string representation of a double-precision floating-point number into this instance at the specified character position.

Insert(Int32, Int16) Insert(Int32, Int16) Insert(Int32, Int16) Insert(Int32, Int16)

在指定的字元位置,將所指定帶正負號之 16 位元整數的字串表示插入這個執行個體。Inserts the string representation of a specified 16-bit signed integer into this instance at the specified character position.

Insert(Int32, Int32) Insert(Int32, Int32) Insert(Int32, Int32) Insert(Int32, Int32)

在指定的字元位置,將所指定帶正負號之 32 位元整數的字串表示插入這個執行個體。Inserts the string representation of a specified 32-bit signed integer into this instance at the specified character position.

Insert(Int32, Int64) Insert(Int32, Int64) Insert(Int32, Int64) Insert(Int32, Int64)

在指定的字元位置上將指定的 64 位元帶正負號的整數之字串表示插入這個執行個體。Inserts the string representation of a 64-bit signed integer into this instance at the specified character position.

Insert(Int32, Object) Insert(Int32, Object) Insert(Int32, Object) Insert(Int32, Object)

在指定的字元位置上將物件的字串表示插入這個執行個體。Inserts the string representation of an object into this instance at the specified character position.

Insert(Int32, ReadOnlySpan<Char>) Insert(Int32, ReadOnlySpan<Char>) Insert(Int32, ReadOnlySpan<Char>) Insert(Int32, ReadOnlySpan<Char>)
Insert(Int32, SByte) Insert(Int32, SByte) Insert(Int32, SByte) Insert(Int32, SByte)

在指定的字元位置,將所指定帶正負號之 8 位元整數的字串表示插入這個執行個體。Inserts the string representation of a specified 8-bit signed integer into this instance at the specified character position.

Insert(Int32, Single) Insert(Int32, Single) Insert(Int32, Single) Insert(Int32, Single)

在指定的字元位置上將單精確度浮點數的字串表示插入這個執行個體。Inserts the string representation of a single-precision floating point number into this instance at the specified character position.

Insert(Int32, String) Insert(Int32, String) Insert(Int32, String) Insert(Int32, String)

在指定的字元位置上將字串插入這個執行個體。Inserts a string into this instance at the specified character position.

Insert(Int32, String, Int32) Insert(Int32, String, Int32) Insert(Int32, String, Int32) Insert(Int32, String, Int32)

在指定的字元位置上將指定字串的一或多個複本插入這個執行個體。Inserts one or more copies of a specified string into this instance at the specified character position.

Insert(Int32, UInt16) Insert(Int32, UInt16) Insert(Int32, UInt16) Insert(Int32, UInt16)

在指定的字元位置,將所指定不帶正負號的 16 位元整數之字串表示插入這個執行個體。Inserts the string representation of a 16-bit unsigned integer into this instance at the specified character position.

Insert(Int32, UInt32) Insert(Int32, UInt32) Insert(Int32, UInt32) Insert(Int32, UInt32)

在指定的字元位置,將所指定不帶正負號的 32 位元整數之字串表示插入這個執行個體。Inserts the string representation of a 32-bit unsigned integer into this instance at the specified character position.

Insert(Int32, UInt64) Insert(Int32, UInt64) Insert(Int32, UInt64) Insert(Int32, UInt64)

在指定的字元位置,將所指定不帶正負號的 64 位元整數之字串表示插入這個執行個體。Inserts the string representation of a 64-bit unsigned integer into this instance at the specified character position.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
Remove(Int32, Int32) Remove(Int32, Int32) Remove(Int32, Int32) Remove(Int32, Int32)

從這個執行個體移除指定的字元範圍。Removes the specified range of characters from this instance.

Replace(Char, Char) Replace(Char, Char) Replace(Char, Char) Replace(Char, Char)

以另一個指定的字元,取代這個執行個體中指定字元的所有項目。Replaces all occurrences of a specified character in this instance with another specified character.

Replace(Char, Char, Int32, Int32) Replace(Char, Char, Int32, Int32) Replace(Char, Char, Int32, Int32) Replace(Char, Char, Int32, Int32)

將這個執行個體的子字串內所有出現的指定字元,取代為另一個指定的字元。Replaces, within a substring of this instance, all occurrences of a specified character with another specified character.

Replace(String, String) Replace(String, String) Replace(String, String) Replace(String, String)

將這個執行個體中所有出現的指定字串取代為另一個指定字串。Replaces all occurrences of a specified string in this instance with another specified string.

Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32)

將這個執行個體的子字串內所有出現的指定字串,取代為另一個指定的字串。Replaces, within a substring of this instance, all occurrences of a specified string with another specified string.

ToString() ToString() ToString() ToString()

將這個執行個體的值轉換為 StringConverts the value of this instance to a String.

ToString(Int32, Int32) ToString(Int32, Int32) ToString(Int32, Int32) ToString(Int32, Int32)

將這個執行個體的子字串值轉換為 StringConverts the value of a substring of this instance to a String.

明確介面實作

ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext)

將還原序列化目前 SerializationInfo 物件所需的資料填入 (Populate) StringBuilder 物件。Populates a SerializationInfo object with the data necessary to deserialize the current StringBuilder object.

適用於

另請參閱