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#範例中的方法,會變更名為value的字串變數值。For 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. StringBuilder物件會維護緩衝區,以容納字串的擴充。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.

重要

雖然類別通常會String比類別提供更佳的效能,但您不StringBuilder應該在每次想要操作字串時自動取代StringStringBuilderAlthough 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 ,可能會提供忽略或不會String改善效能。In 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缺少像IndexOfStartsWith之類的搜尋方法。The 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物件目前包含的字元數。 StringBuilder.LengthThe 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無法為物件配置任何進一步的記憶體,而且嘗試新增字元,或將它展開超過其最大容量ArgumentOutOfRangeException時,會擲OutOfMemoryException回或例外狀況。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個字元,而其最大容量超過2000000000個字元。The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters. 附加字串 "This is a 句子"。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. 然後,程式碼會附加字串「此為額外的句子。」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.MaxValue為。The 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 value所定義。Defined 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 value所定義。Defined 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. 它會將十個亂數字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物件內容的方法: StringBuilderThe StringBuilder class includes the following methods for expanding the contents of a StringBuilder object:

  • 方法會將字串、子字串、字元陣列、字元陣列的一部分、重複多次的單一字元,或基本資料類型的字串表示附加StringBuilder至物件。 AppendThe 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.

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

  • 方法會將StringBuilder 複合格式字串附加至物件。 AppendFormatThe 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.

  • 方法會在StringBuilder物件中的指定位置,插入字串、子字串、字串的多個重複、字元陣列、字元陣列的一部分,或基本資料類型的字串表示。 InsertThe 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和方法來展開物件的文字。StringBuilderThe 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實例大小的方法。 StringBuilderThe StringBuilder class includes methods that can reduce the size of the current StringBuilder instance. 方法會移除所有字元,並Length將屬性設定為零。 ClearThe 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物件或特定字元範圍中所有出現的字元或字串。 StringBuilder.ReplaceThe 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

String.StartsWith String.Contains String.IndexOf類別不包含類似于類別String所提供的、和方法的方法,可讓您搜尋物件中的特定字元或子字串。 StringBuilderThe 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.
將物件轉換String為物件, String並在物件上執行修改。 StringBuilderConvert 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物件String轉換成物件。 StringBuilder.ToStringCall the StringBuilder.ToString method to convert the StringBuilder object to a String object. 您可以使用String.LastIndexOfString.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. 由於和StringBuilder String物件都使用 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物件中的字元範圍。 StringBuilder.Chars[Int32]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呼叫方法以StringStringBuilder物件轉換為物件,並在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 和更新版本中,當您藉由呼叫StringBuilderStringBuilder(Int32, Int32)函式來具現化物件時, StringBuilder實例的長度和容量都可以成長超過其MaxCapacity的值property.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>)

將所指定唯讀字元記憶體區域的字串表示附加至這個執行個體。Appends the string representation of a specified read-only character memory region to this instance.

Append(ReadOnlySpan<Char>) Append(ReadOnlySpan<Char>) Append(ReadOnlySpan<Char>) Append(ReadOnlySpan<Char>)

將所指定唯讀字元範圍的字串表示附加至這個執行個體。Appends the string representation of a specified read-only character span to this instance.

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)

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

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

將所指定字串產生器內的子字串複本附加至這個執行個體。Appends a copy of a substring within a specified string builder to this instance.

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()

傳回物件,可用來逐一查看從這個 StringBuilder 執行個體建立的 ReadOnlyMemory<Char> 中所表示字元區塊。Returns an object that can be used to iterate through the chunks of characters represented in a ReadOnlyMemory<Char> created from this StringBuilder instance.

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.

適用於

另請參閱