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:

字符串和 StringBuilder 类型The String and StringBuilder types

尽管StringBuilderString二者都表示序列的字符,它们的实现方式有所不同。Although StringBuilder and String both represent sequences of characters, they are implemented differently. String 是不可变类型。String is an immutable type. 也就是说,每个操作,它可修改String对象实际上会创建一个新的字符串。That is, each operation that appears to modify a String object actually creates a new string.

例如,在调用String.Concat方法在下面的 C# 示例显示名为的字符串变量的值更改valueFor example, the call to the String.Concat method in the following C# example appears to change the value of a string variable named value. 事实上,Concat方法将返回value对象具有不同的值和从地址value传递给方法的对象。In fact, the Concat method returns a value object that has a different value and address from the value object that was passed to the method. 请注意,必须使用编译该示例/unsafe编译器选项。Note that the example must be compiled using the /unsafe compiler option.

using System;

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

对于执行广泛的字符串操作 (例如修改在循环中多次的字符串的应用) 的例程,重复修改字符串可以精确对显著的性能产生负面影响。For routines that perform extensive string manipulation (such as apps that modify a string numerous times in a loop), modifying a string repeatedly can exact a significant performance penalty. 替代方法是使用StringBuilder,它是一个可变字符串类。The alternative is to use StringBuilder, which is a mutable string class. 可变性意味着,一旦创建类的实例后,它可以修改通过追加、 删除、 替换或插入字符。Mutability means that once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters. 一个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.

重要

尽管StringBuilder类通常提供更好的性能比String类,您应该不会自动替换StringStringBuilder每当你想要操作的字符串。Although the StringBuilder class generally offers better performance than the String class, you should not automatically replace String with StringBuilder whenever you want to manipulate strings. 性能取决于字符串,并将其分配新字符串、 执行您的应用程序的系统和操作的类型的内存量的大小。Performance depends on the size of the string, the amount of memory to be allocated for the new string, the system on which your app is executing, and the type of operation. 您应该准备好测试应用程序以确定是否StringBuilder实际上提供了显著改善性能。You should be prepared to test your app to determine whether StringBuilder actually offers a significant performance improvement.

请考虑使用String类在这些情况下:Consider using the String class under these conditions:

  • 当您的应用程序将对字符串进行的更改数很小。When the number of changes that your app will make to a string is small. 在这些情况下,StringBuilder可能可以忽略不计的产品/服务或对任何性能改进StringIn these cases, StringBuilder might offer negligible or no performance improvement over String.

  • 当正在执行固定的数量的串联操作中,尤其是对于字符串文本。When you are performing a fixed number of concatenation operations, particularly with string literals. 在这种情况下,编译器可能将合并到单个操作的串联操作。In this case, the compiler might combine the concatenation operations into a single operation.

  • 当必须执行广泛的搜索操作时要构建您的字符串。When you have to perform extensive search operations while you are building your string. StringBuilder类缺少搜索方法,如IndexOfStartsWithThe StringBuilder class lacks search methods such as IndexOf or StartsWith. 您必须将转换StringBuilder对象传递给String为这些操作,这可以抵消性能受益于使用StringBuilderYou'll have to convert the StringBuilder object to a String for these operations, and this can negate the performance benefit from using StringBuilder. 有关详细信息,请参阅StringBuilder 对象中搜索的文本部分。For more information, see the Searching the text in a StringBuilder object section.

请考虑使用StringBuilder类在这些情况下:Consider using the StringBuilder class under these conditions:

  • 如果期望您的应用程序在设计时 (例如,在使用一个循环来连接包含用户输入的字符串的随机数字时) 对字符串进行的更改数未知。When you expect your app to make an unknown number of changes to a string at design time (for example, when you are using a loop to concatenate a random number of strings that contain user input).

  • 当您希望对字符串进行大量更改您的应用程序。When you expect your app to make a significant number of changes to a string.

StringBuilder 的工作原理How StringBuilder works

StringBuilder.Length属性指示的字符数StringBuilder当前包含的对象。The StringBuilder.Length property indicates the number of characters the StringBuilder object currently contains. 如果您添加到字符StringBuilder对象,直至等于的大小,其长度增加StringBuilder.Capacity属性,定义的对象可包含的字符数。If you add characters to the StringBuilder object, its length increases until it equals the size of the StringBuilder.Capacity property, which defines the number of characters that the object can contain. 如果添加了字符数导致的长度StringBuilder对象超过其当前容量、 新的内存分配,值Capacity加倍属性时,新的字符添加到StringBuilder对象,并且其Length调整属性。If the number of added characters causes the length of the StringBuilder object to exceed its current capacity, new memory is allocated, the value of the Capacity property is doubled, new characters are added to the StringBuilder object, and its Length property is adjusted. 额外的内存StringBuilder直到它达到定义的值动态分配对象StringBuilder.MaxCapacity属性。Additional memory for the StringBuilder object is allocated dynamically until it reaches the value defined by the StringBuilder.MaxCapacity property. 当达到最大容量时,可以为分配任何进一步的内存StringBuilder对象,并尝试添加字符或扩展到超过其最大容量引发任一ArgumentOutOfRangeExceptionOutOfMemoryException异常。When the maximum capacity is reached, no further memory can be allocated for the StringBuilder object, and trying to add characters or expand it beyond its maximum capacity throws either an ArgumentOutOfRangeException or an OutOfMemoryException exception.

下面的示例演示如何StringBuilder对象分配新内存,并动态地增加其容量,随着分配给该对象的字符串的扩展。The following example illustrates how a StringBuilder object allocates new memory and increases its capacity dynamically as the string assigned to the object expands. 该代码会创建StringBuilder对象通过调用其默认 (无参数) 构造函数。The code creates a StringBuilder object by calling its default (parameterless) constructor. 此对象的默认容量为 16 个字符,其最大容量为超过 20 亿个字符。The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters. 将字符串追加"这一个句子"。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.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参数或valueDefined by the capacity parameter or value. Length两者中较大。Length, whichever is greater. Int32.MaxValue
StringBuilder(String, Int32, Int32, Int32) value 定义。Defined by value. Substring(startIndex, length)Substring(startIndex, length) 定义由capacity参数或valueDefined by the capacity parameter or value. Length两者中较大。Length, whichever is greater. 通过定义maxCapacity参数Defined by the maxCapacity parameter

下面的示例使用三个构造函数重载来实例化StringBuilder对象。The following example uses three of these constructor overloads to instantiate StringBuilder objects.

using System;
using System.Text;

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

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

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

调用 StringBuilder 方法Calling StringBuilder methods

在修改字符串的方法的大多数StringBuilder实例返回到该同一实例的引用。Most of the methods that modify the string in a StringBuilder instance return a reference to that same instance. 这使您可以调用StringBuilder两种方法中的方法:This enables you to call StringBuilder methods in two ways:

  • 可以进行单个方法调用,并忽略返回值,如以下示例所示。You can make individual method calls and ignore the return value, as the following example does.

    using System;
    using System.Text;
    
    public class Example
    {
       public static void Main()
       {
          StringBuilder sb = new StringBuilder();
          sb.Append("This is the beginning of a sentence, ");
          sb.Replace("the beginning of ", "");
          sb.Insert(sb.ToString().IndexOf("a ") + 2, "complete ");
          sb.Replace(",", ".");
          Console.WriteLine(sb.ToString());
       }
    }
    // The example displays the following output:
    //        This is a complete sentence.
    
    Imports System.Text
    
    Module Example
       Public Sub Main()
          Dim sb As New StringBuilder()
          sb.Append("This is the beginning of a sentence, ")
          sb.Replace("the beginning of ", "")
          sb.Insert(sb.ToString().IndexOf("a ") + 2, "complete ")
          sb.Replace(",", ".")
          Console.WriteLine(sb.ToString())
       End Sub
    End Module
    ' The example displays the following output:
    '       This is a complete sentence.
    
  • 单个语句中,可以进行一系列方法调用。You can make a series of method calls in a single statement. 这会非常方便,如果你想要编写用于链接在连续的操作的单个语句。This can be convenient if you want to write a single statement that chains successive operations. 下面的示例将上一示例中的三个方法调用合并到一行代码。The following example consolidates three method calls from the previous example into a single line of code.

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

执行 StringBuilder 操作Performing StringBuilder operations

可以使用的方法StringBuilder类来循环访问、 添加、 删除或修改中的字符StringBuilder对象。You can use the methods of the StringBuilder class to iterate, add, delete, or modify characters in a StringBuilder object.

循环访问 StringBuilder 字符Iterating StringBuilder characters

您可以访问中的字符StringBuilder对象使用StringBuilder.Chars[Int32]属性。You can access the characters in a StringBuilder object by using the StringBuilder.Chars[Int32] property. 在 C# 中,Chars[Int32]是一个索引器; 在 Visual Basic 中,它是默认属性的StringBuilder类。In C#, Chars[Int32] is an indexer; in Visual Basic, it is the default property of the StringBuilder class. 这使您可以设置或检索个别字符使用它们的索引,而无需显式引用Chars[Int32]属性。This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the Chars[Int32] property. 中的字符StringBuilder对象从索引 0 (零) 开始,继续索引Length-1。Characters in a StringBuilder object begin at index 0 (zero) and continue to index Length - 1.

下面的示例演示Chars[Int32]属性。The following example illustrates the Chars[Int32] property. 将追加到 10 个随机数字StringBuilder对象,然后循环访问每个字符。It appends ten random numbers to a StringBuilder object, and then iterates each character. 如果该字符的 Unicode 类别是UnicodeCategory.DecimalDigitNumber,它按 1 递减数 (或如果其值为 0 的数字更改为 9)。If the character's Unicode category is UnicodeCategory.DecimalDigitNumber, it decreases the number by 1 (or changes the number to 9 if its value is 0). 该示例显示的内容StringBuilder对象同时之前和之后的单个字符的值已更改。The example displays the contents of the StringBuilder object both before and after the values of individual characters were changed.

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

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

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

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

在以下情况下,通过 Chars[Int32] 属性使用基于字符的索引可能会非常缓慢:Using character-based indexing with the Chars[Int32] property can be extremely slow under the following conditions:

因为每次字符访问都会遍历区块的整个链接列表以查找要索引到的正确缓冲区,所以性能受到严重影响。Performance is severely impacted because each character access walks the entire linked list of chunks to find the correct buffer to index into.

备注

即使对于大型“笨重的”StringBuilder 对象,使用 Chars[Int32] 属性对一个或少量字符进行基于索引的访问几乎不影响性能;一般情况下,它是 0(n) 操作 。Even for a large "chunky" StringBuilder object, using the Chars[Int32] property for index-based access to one or a small number of characters has a negligible performance impact; typically, it is an 0(n) operation. 当迭代 StringBuilder 对象中的字符时,会对性能造成显著的影响,这是 O(n^2) 操作 。The significant performance impact occurs when iterating the characters in the StringBuilder object, which is an O(n^2) operation.

如果通过 StringBuilder 对象在使用基于字符的索引时遇到性能问题,可以使用以下任一解决方法:If you encounter performance issues when using character-based indexing with StringBuilder objects, you can use any of the following workarounds:

  • 通过调用 ToString 方法,将 StringBuilder 实例转换为 String,然后访问字符串中的字符。Convert the StringBuilder instance to a String by calling the ToString method, then access the characters in the string.

  • 将现有的 StringBuilder 对象的内容复制到新的预调整大小的 StringBuilder 对象。Copy the contents of the existing StringBuilder object to a new pre-sized StringBuilder object. 由于新的 StringBuilder 对象并不笨重,因此可以提升性能。Performance improves because the new StringBuilder object is not chunky. 例如:For example:

    // sbOriginal is the existing StringBuilder object
    var sbNew = new StringBuilder(sbOriginal.ToString(), sbOriginal.Length);
    
    ' sbOriginal is the existing StringBuilder object
    Dim sbNew = New StringBuilder(sbOriginal.ToString(), sbOriginal.Length)
    
  • 通过调用 StringBuilder(Int32) 构造函数,将 StringBuilder 对象的初始容量设置为约等于其最大预期大小的值。Set the initial capacity of the StringBuilder object to a value that is approximately equal to its maximum expected size by calling the StringBuilder(Int32) constructor. 请注意,即使 StringBuilder 很少达到其最大容量,它仍会分配整个内存块。Note that this allocates the entire block of memory even if the StringBuilder rarely reaches its maximum capacity.

将文本添加到 StringBuilder 对象Adding text to a StringBuilder object

StringBuilder类包括以下方法来扩展的内容StringBuilder对象:The StringBuilder class includes the following methods for expanding the contents of a StringBuilder object:

  • Append方法将追加字符串、 一个子字符串、 字符数组、 字符数组的一部分的单个字符重复多次,或的字符串表示形式的基元数据类型更改为StringBuilder对象。The Append method appends a string, a substring, a character array, a portion of a character array, a single character repeated multiple times, or the string representation of a primitive data type to a StringBuilder object.

  • AppendLine方法将行终止符或行终止符字符串追加StringBuilder对象。The AppendLine method appends a line terminator or a string along with a line terminator to a StringBuilder object.

  • AppendFormat方法将追加复合格式字符串StringBuilder对象。The AppendFormat method appends a composite format string to a StringBuilder object. 字符串表示形式的结果字符串中包含的对象可以反映当前系统区域性或指定的区域性的格式设置约定。The string representations of objects included in the result string can reflect the formatting conventions of the current system culture or a specified culture.

  • Insert方法插入一个字符串,子字符串,字符串的多个重复的字符数组、 字符数组的部分或基元数据的字符串表示形式中指定位置处键入StringBuilder对象。The Insert method inserts a string, a substring, multiple repetitions of a string, a character array, a portion of a character array, or the string representation of a primitive data type at a specified position in the StringBuilder object. 按从零开始的索引定义位置。The position is defined by a zero-based index.

下面的示例使用AppendAppendLineAppendFormat,和Insert方法以展开的文本StringBuilder对象。The following example uses the Append, AppendLine, AppendFormat, and Insert methods to expand the text of a StringBuilder object.

using System;
using System.Text;

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

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

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

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

从 StringBuilder 对象中删除文本Deleting text from a StringBuilder object

StringBuilder类包括可以减少的当前大小的方法StringBuilder实例。The StringBuilder class includes methods that can reduce the size of the current StringBuilder instance. Clear方法中删除所有字符,并设置Length属性设置为零。The Clear method removes all characters and sets the Length property to zero. Remove方法中删除指定的数量的特定索引位置开始的字符。The Remove method deletes a specified number of characters starting at a particular index position. 此外,从末尾删除字符StringBuilder对象通过设置其Length属性的值小于当前实例的长度。In addition, you can remove characters from the end of a StringBuilder object by setting its Length property to a value that is less than the length of the current instance.

以下示例将删除的某些从文本StringBuilder对象,显示其生成的容量、 最大容量和长度属性值,然后调用Clear方法来删除中的所有字符StringBuilder对象。The following example removes some of the text from a StringBuilder object, displays its resulting capacity, maximum capacity, and length property values, and then calls the Clear method to remove all the characters from the StringBuilder object.

using System;
using System.Text;

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

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

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

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

修改 StringBuilder 对象中的文本Modifying the text in a StringBuilder object

StringBuilder.Replace方法替换所有出现的字符或字符串中整个StringBuilder对象或在特定的字符范围内。The StringBuilder.Replace method replaces all occurrences of a character or a string in the entire StringBuilder object or in a particular character range. 下面的示例使用Replace方法中使用问号 (?) 替换所有感叹号 (!)StringBuilder对象。The following example uses the Replace method to replace all exclamation points (!) with question marks (?) in the StringBuilder object.

using System;
using System.Text;

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

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

StringBuilder 对象中搜索的文本Searching the text in a StringBuilder object

StringBuilder类不包括方法类似于String.ContainsString.IndexOf,和String.StartsWith提供的方法String类,该类,您可以搜索特定字符或子字符串的对象。The StringBuilder class does not include methods similar to the String.Contains, String.IndexOf, and String.StartsWith methods provided by the String class, which allow you to search the object for a particular character or a substring. 确定是否存在或启动的子字符串的字符位置需要您搜索String使用字符串搜索方法或正则表达式方法的值。Determining the presence or starting character position of a substring requires that you search a String value by using either a string search method or a regular expression method. 有四种方法来实现此类搜索,如下表所示。There are four ways to implement such searches, as the following table shows.

技术Technique 专业人员Pros 缺点Cons
将它们添加到之前搜索的字符串值StringBuilder对象。Search string values before adding them to the StringBuilder object. 可用于确定是否存在某个子字符串。Useful for determining whether a substring exists. 不能使用子字符串的索引位置很重要。Cannot be used when the index position of a substring is important.
调用ToString并搜索返回String对象。Call ToString and search the returned String object. 易于使用如果分配到的所有文本StringBuilder对象,并开始对其进行修改。Easy to use if you assign all the text to a StringBuilder object, and then begin to modify it. 重复调用不便于ToString如果您必须进行修改的所有文本都添加到之前StringBuilder对象。Cumbersome to repeatedly call ToString if you must make modifications before all text is added to the StringBuilder object.

您必须记得从末尾StringBuilder对象的文本,如果您要做的更改。You must remember to work from the end of the StringBuilder object's text if you're making changes.
使用Chars[Int32]属性按顺序搜索的字符范围。Use the Chars[Int32] property to sequentially search a range of characters. 如果您关心的单个字符或小的子字符串,这很有用。Useful if you're concerned with individual characters or a small substring. 如果要搜索的字符数较大,或者搜索逻辑很复杂繁琐。Cumbersome if the number of characters to search is large or if the search logic is complex.

已变得非常大而通过重复进行方法调用的对象的性能非常不佳的结果。Results in very poor performance for objects that have grown very large through repeated method calls.
将转换StringBuilder对象传递给String对象,并在执行修改String对象。Convert the StringBuilder object to a String object, and perform modifications on the String object. 如果修改的数量较少时很有用。Useful if the number of modifications is small. 求反的性能优势StringBuilder类如果的修改量很大。Negates the performance benefit of the StringBuilder class if the number of modifications is large.

让我们看一下中更详细地介绍这些技术。Let's examine these techniques in greater detail.

  • 如果搜索的目标是确定是否存在某个特定的子字符串的 (即,如果您不感兴趣子字符串的位置),可以搜索字符串之前将它们存储在StringBuilder对象。If the goal of the search is to determine whether a particular substring exists (that is, if you aren't interested in the position of the substring), you can search strings before storing them in the StringBuilder object. 下面的示例提供了一种可能实现。The following example provides one possible implementation. 它定义StringBuilderFinder类的构造函数传递的引用StringBuilder对象和要在字符串中找到的子字符串。It defines a StringBuilderFinder class whose constructor is passed a reference to a StringBuilder object and the substring to find in the string. 在这种情况下,此示例尝试确定是否记录的温度华氏或摄氏温度,并将相应的介绍性文本添加到的开头StringBuilder对象。In this case, the example tries to determine whether recorded temperatures are in Fahrenheit or Celsius, and adds the appropriate introductory text to the beginning of the StringBuilder object. 随机数生成器用于选择包含摄氏度或华氏度中的数据的数组。A random number generator is used to select an array that contains data in either degrees Celsius or degrees Fahrenheit.

    using System;
    using System.Text;
    
    public class Example
    {
       public static void Main()
       {
          Random rnd = new Random();
          string[] tempF = { "47.6F", "51.3F", "49.5F", "62.3F" };
          string[] tempC = { "21.2C", "16.1C", "23.5C", "22.9C" };
          string[][] temps = { tempF, tempC }; 
    
          StringBuilder sb = new StringBuilder();
          var f = new StringBuilderFinder(sb, "F");
          var baseDate = new DateTime(2013, 5, 1); 
          String[] temperatures = temps[rnd.Next(2)];
          bool isFahrenheit = false;
          foreach (var temperature in temperatures) {
             if (isFahrenheit)
                sb.AppendFormat("{0:d}: {1}\n", baseDate, temperature);
             else
                isFahrenheit = f.SearchAndAppend(String.Format("{0:d}: {1}\n", 
                                                 baseDate, temperature));
             baseDate = baseDate.AddDays(1);
          }            
          if (isFahrenheit) {
             sb.Insert(0, "Average Daily Temperature in Degrees Fahrenheit");
             sb.Insert(47, "\n\n");
          }
          else {
             sb.Insert(0, "Average Daily Temperature in Degrees Celsius");
             sb.Insert(44, "\n\n");
          }   
          Console.WriteLine(sb.ToString());
       }
    }
    
    public class StringBuilderFinder
    {
       private StringBuilder sb;
       private String text;
       
       public StringBuilderFinder(StringBuilder sb, String textToFind)
       {
          this.sb = sb;
          this.text = textToFind;
       }
       
       public bool SearchAndAppend(String stringToSearch)
       {
          sb.Append(stringToSearch);
          return stringToSearch.Contains(text);
       }
    }
    // The example displays output similar to the following:
    //    Average Daily Temperature in Degrees Celsius
    //    
    //    5/1/2013: 21.2C
    //    5/2/2013: 16.1C
    //    5/3/2013: 23.5C
    //    5/4/2013: 22.9C
    
    Imports System.Text
    
    Module Example
       Public Sub Main()
          Dim rnd As New Random()
          Dim tempF() As String = { "47.6F", "51.3F", "49.5F", "62.3F" }
          Dim tempC() As String = { "21.2C", "16.1C", "23.5C", "22.9C" }
          Dim temps()() As String = { tempF, tempC } 
    
          Dim sb As StringBuilder = New StringBuilder()
          Dim f As New StringBuilderFinder(sb, "F")
          Dim baseDate As New DateTime(2013, 5, 1) 
          Dim temperatures() As String = temps(rnd.Next(2))
          Dim isFahrenheit As Boolean = False
          For Each temperature In temperatures
             If isFahrenheit Then
                sb.AppendFormat("{0:d}: {1}{2}", baseDate, temperature, vbCrLf)
             Else
                isFahrenheit = f.SearchAndAppend(String.Format("{0:d}: {1}{2}", 
                                                 baseDate, temperature, vbCrLf))
             End If
             baseDate = baseDate.AddDays(1)
          Next            
          If isFahrenheit Then
             sb.Insert(0, "Average Daily Temperature in Degrees Fahrenheit")
             sb.Insert(47, vbCrLf + vbCrLf)
          Else
             sb.Insert(0, "Average Daily Temperature in Degrees Celsius")
             sb.Insert(44, vbCrLf + vbCrLf)
          End If   
          Console.WriteLine(sb.ToString())
       End Sub
    End Module
    
    Public Class StringBuilderFinder
       Private sb As StringBuilder
       Private text As String
       
       Public Sub New(sb As StringBuilder, textToFind As String)
          Me.sb = sb
          text = textToFind
       End Sub
       
       Public Function SearchAndAppend(stringToSearch As String) As Boolean
          sb.Append(stringToSearch)
          Return stringToSearch.Contains(text)
       End Function
    End Class
    ' The example displays output similar to the following:
    '    Average Daily Temperature in Degrees Celsius
    '    
    '    5/1/2013: 21.2C
    '    5/2/2013: 16.1C
    '    5/3/2013: 23.5C
    '    5/4/2013: 22.9C
    
  • 调用StringBuilder.ToString方法将转换StringBuilder对象传递给String对象。Call the StringBuilder.ToString method to convert the StringBuilder object to a String object. 可以使用类似于方法搜索字符串String.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. 因为这两StringBuilderString对象使用 utf-16 编码用于存储字符,子字符串的索引位置的字符和正则表达式匹配项是在这两个对象相同。Because both StringBuilder and String objects use UTF-16 encoding to store characters, the index positions of characters, substrings, and regular expression matches are the same in both objects. 这使您可以使用StringBuilder方法,以便可以在同一位置中找到该文本的更改String对象。This enables you to use StringBuilder methods to make changes at the same position at which that text is found in the String object.

    备注

    如果采用这种方法,你应从结尾处起作用StringBuilder对象到其开始,因此无需重复转换StringBuilder为字符串的对象。If you adopt this approach, you should work from the end of the StringBuilder object to its beginning so that you don't have to repeatedly convert the StringBuilder object to a string.

    下面的示例阐释了这种方法。The following example illustrates this approach. 它将存储在英语字母表中的每个字母的四个匹配项StringBuilder对象。It stores four occurrences of each letter of the English alphabet in a StringBuilder object. 然后将转换为文本String对象,并使用正则表达式来标识每个四个字符序列的起始位置。It then converts the text to a String object and uses a regular expression to identify the starting position of each four-character sequence. 最后,它将添加下划线前除第一个序列,每个四个字符序列,并将转换为大写的序列的第一个字符。Finally, it adds an underscore before each four-character sequence except for the first sequence, and converts the first character of the sequence to uppercase.

    using System;
    using System.Text;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          // Create a StringBuilder object with 4 successive occurrences 
          // of each character in the English alphabet. 
          StringBuilder sb = new StringBuilder();
          for (ushort ctr = (ushort)'a'; ctr <= (ushort) 'z'; ctr++)
             sb.Append(Convert.ToChar(ctr), 4);
          
          // Create a parallel string object.
          String sbString = sb.ToString();
          // Determine where each new character sequence begins.
          String pattern = @"(\w)\1+";
          MatchCollection matches = Regex.Matches(sbString, pattern);
    
          // Uppercase the first occurrence of the sequence, and separate it
          // from the previous sequence by an underscore character.
          for (int ctr = matches.Count - 1; ctr >= 0; ctr--) { 
             Match m = matches[ctr];
             sb[m.Index] = Char.ToUpper(sb[m.Index]);
             if (m.Index > 0) sb.Insert(m.Index, "_");
          }
          // Display the resulting string.
          sbString = sb.ToString();
          int line = 0;
          do {
             int nChars = line * 80 + 79 <= sbString.Length ? 
                                 80 : sbString.Length - line * 80;
             Console.WriteLine(sbString.Substring(line * 80, nChars));
             line++;
          } while (line * 80 < sbString.Length);
       }
    }
    // The example displays the following output:
    //    Aaaa_Bbbb_Cccc_Dddd_Eeee_Ffff_Gggg_Hhhh_Iiii_Jjjj_Kkkk_Llll_Mmmm_Nnnn_Oooo_Pppp_
    //    Qqqq_Rrrr_Ssss_Tttt_Uuuu_Vvvv_Wwww_Xxxx_Yyyy_Zzzz
    
    Imports System.Text
    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          ' Create a StringBuilder object with 4 successive occurrences 
          ' of each character in the English alphabet. 
          Dim sb As New StringBuilder()
          For ctr As UShort = AscW("a") To Ascw("z")
             sb.Append(ChrW(ctr), 4)
          Next    
          ' Create a parallel string object.
          Dim sbString As String = sb.ToString()
          ' Determine where each new character sequence begins.
          Dim pattern As String = "(\w)\1+"
          Dim matches As MatchCollection = Regex.Matches(sbString, pattern)
    
          ' Uppercase the first occurrence of the sequence, and separate it
          ' from the previous sequence by an underscore character.
          For ctr As Integer = matches.Count - 1 To 0 Step -1 
             Dim m As Match = matches(ctr)
             sb.Chars(m.Index) = Char.ToUpper(sb.Chars(m.index))
             If m.Index > 0 Then sb.Insert(m.Index, "_")
          Next
          ' Display the resulting string.
          sbString = sb.ToString()
          Dim line As Integer = 0
          Do
             Dim nChars As Integer = If(line * 80 + 79 <= sbString.Length, 
                                        80, sbString.Length - line * 80)
             Console.WriteLine(sbString.Substring(line * 80, nChars))
             line += 1
          Loop While line * 80 < sbString.Length
       End Sub
    End Module
    ' The example displays the following output:
    '    Aaaa_Bbbb_Cccc_Dddd_Eeee_Ffff_Gggg_Hhhh_Iiii_Jjjj_Kkkk_Llll_Mmmm_Nnnn_Oooo_Pppp_
    '    Qqqq_Rrrr_Ssss_Tttt_Uuuu_Vvvv_Wwww_Xxxx_Yyyy_Zzzz
    
  • 使用StringBuilder.Chars[Int32]属性按顺序搜索中的字符范围StringBuilder对象。Use the StringBuilder.Chars[Int32] property to sequentially search a range of characters in a StringBuilder object. 如果要在其中搜索的字符数很大或搜索逻辑是特别复杂,这种方法可能不可行。This approach may not be practical if the number of characters to be searched is large or the search logic is particularly complex. 逐字符基于索引的访问对性能产生影响非常大,chunkedStringBuilder对象,请参阅的文档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>)
Append(ReadOnlySpan<Char>) Append(ReadOnlySpan<Char>) Append(ReadOnlySpan<Char>) Append(ReadOnlySpan<Char>)
Append(SByte) Append(SByte) Append(SByte) Append(SByte)

向此实例追加指定的 8 位有符号整数的字符串表示形式。Appends the string representation of a specified 8-bit signed integer to this instance.

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

向此实例追加指定的单精度浮点数的字符串表示形式。Appends the string representation of a specified single-precision floating-point number to this instance.

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

向此实例追加指定字符串的副本。Appends a copy of the specified string to this instance.

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

向此实例追加指定子字符串的副本。Appends a copy of a specified substring to this instance.

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

向此实例追加指定的 16 位无符号整数的字符串表示形式。Appends the string representation of a specified 16-bit unsigned integer to this instance.

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

向此实例追加指定的 32 位无符号整数的字符串表示形式。Appends the string representation of a specified 32-bit unsigned integer to this instance.

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

向此实例追加指定的 64 位无符号整数的字符串表示形式。Appends the string representation of a specified 64-bit unsigned integer to this instance.

AppendFormat(IFormatProvider, String, Object) AppendFormat(IFormatProvider, String, Object) AppendFormat(IFormatProvider, String, Object) AppendFormat(IFormatProvider, String, Object)

向此实例追加通过处理复合格式字符串(包含零个或更多格式项)而返回的字符串。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每个格式项都使用指定的格式提供程序替换为单个参数的字符串表示形式。Each format item is replaced by the string representation of a single argument using a specified format provider.

AppendFormat(IFormatProvider, String, Object, Object) AppendFormat(IFormatProvider, String, Object, Object) AppendFormat(IFormatProvider, String, Object, Object) AppendFormat(IFormatProvider, String, Object, Object)

向此实例追加通过处理复合格式字符串(包含零个或更多格式项)而返回的字符串。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每个格式项都使用指定的格式提供程序替换为两个参数中任一个的字符串表示形式。Each format item is replaced by the string representation of either of two arguments using a specified format provider.

AppendFormat(IFormatProvider, String, Object, Object, Object) AppendFormat(IFormatProvider, String, Object, Object, Object) AppendFormat(IFormatProvider, String, Object, Object, Object) AppendFormat(IFormatProvider, String, Object, Object, Object)

向此实例追加通过处理复合格式字符串(包含零个或更多格式项)而返回的字符串。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每个格式项都使用指定的格式提供程序替换为三个参数中任一个的字符串表示形式。Each format item is replaced by the string representation of either of three arguments using a specified format provider.

AppendFormat(IFormatProvider, String, Object[]) AppendFormat(IFormatProvider, String, Object[]) AppendFormat(IFormatProvider, String, Object[]) AppendFormat(IFormatProvider, String, Object[])

向此实例追加通过处理复合格式字符串(包含零个或更多格式项)而返回的字符串。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每个格式项都使用指定的格式提供程序由参数数组中相应参数的字符串表示形式替换。Each format item is replaced by the string representation of a corresponding argument in a parameter array using a specified format provider.

AppendFormat(String, Object) AppendFormat(String, Object) AppendFormat(String, Object) AppendFormat(String, Object)

向此实例追加通过处理复合格式字符串(包含零个或更多格式项)而返回的字符串。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每个格式项都替换为一个参数的字符串表示形式。Each format item is replaced by the string representation of a single argument.

AppendFormat(String, Object, Object) AppendFormat(String, Object, Object) AppendFormat(String, Object, Object) AppendFormat(String, Object, Object)

向此实例追加通过处理复合格式字符串(包含零个或更多格式项)而返回的字符串。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每个格式项都替换为这两个参数中任意一个参数的字符串表示形式。Each format item is replaced by the string representation of either of two arguments.

AppendFormat(String, Object, Object, Object) AppendFormat(String, Object, Object, Object) AppendFormat(String, Object, Object, Object) AppendFormat(String, Object, Object, Object)

向此实例追加通过处理复合格式字符串(包含零个或更多格式项)而返回的字符串。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每个格式项都替换为这三个参数中任意一个参数的字符串表示形式。Each format item is replaced by the string representation of either of three arguments.

AppendFormat(String, Object[]) AppendFormat(String, Object[]) AppendFormat(String, Object[]) AppendFormat(String, Object[])

向此实例追加通过处理复合格式字符串(包含零个或更多格式项)而返回的字符串。Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. 每个格式项都由参数数组中相应参数的字符串表示形式替换。Each format item is replaced by the string representation of a corresponding argument in a parameter array.

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

将默认的行终止符追加到当前 StringBuilder 对象的末尾。Appends the default line terminator to the end of the current StringBuilder object.

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

将后面跟有默认行终止符的指定字符串的副本追加到当前 StringBuilder 对象的末尾。Appends a copy of the specified string followed by the default line terminator to the end of the current StringBuilder object.

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

从当前 StringBuilder 实例中移除所有字符。Removes all characters from the current StringBuilder instance.

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

将此实例的指定段中的字符复制到目标 Char 数组的指定段中。Copies the characters from a specified segment of this instance to a specified segment of a destination Char array.

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

确保 StringBuilder 的此实例的容量至少是指定值。Ensures that the capacity of this instance of StringBuilder is at least the specified value.

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

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

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

返回一个值,该值指示此实例中的字符是否等于指定的只读字符范围中的字符。Returns a value indicating whether the characters in this instance are equal to the characters in a specified read-only character span.

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

返回一个值,该值指示此实例是否等于指定的对象。Returns a value indicating whether this instance is equal to a specified object.

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

作为默认哈希函数。Serves as the default hash function.

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

获取当前实例的 TypeGets the Type of the current instance.

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

将布尔值的字符串表示形式插入到此实例中的指定字符位置。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.

适用于

另请参阅