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比类提供更好的性能,但你不应在String每次需要操作字符串时自动将替换为StringBuilderStringBuilderAlthough 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. 类缺少搜索方法, IndexOf如或StartsWithStringBuilderThe StringBuilder class lacks search methods such as IndexOf or StartsWith. 对于这些操作,必须将StringBuilder对象转换StringBuilder为,这可能会使使用不会带来性能优势。 StringYou'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对象分配更多的内存,尝试添加字符或将其扩展到超出其最大容量后,会引发OutOfMemoryException ArgumentOutOfRangeException或例外。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. 然后,该代码将追加字符串 "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对象的最终大小可能会变得非常大,通常会超出几兆字节。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. 它将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:

  • 方法追加字符串、子字符串、字符数组、字符数组的一部分、多次重复的单个字符或基元数据类型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类包括可以减少的当前大小的方法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对象中删除一些文本、显示其生成的容量、最大容量和 length 属性值,然后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.IndexOf String.StartsWith String.Contains类不包括与类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调用方法将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)

向此实例追加指定的布尔值的字符串表示形式。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)

返回一个值,该值指示此实例是否等于指定的对象。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)

将布尔值的字符串表示形式插入到此实例中的指定字符位置。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 的浅表副本。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 对象来反序列化当前 StringBuilder 对象。Populates a SerializationInfo object with the data necessary to deserialize the current StringBuilder object.

适用于

另请参阅