StringBuilder Třída

Definice

Představuje proměnlivý řetězec znaků.Represents a mutable string of characters. Tuto třídu nelze zdědit.This class cannot be inherited.

public ref class StringBuilder sealed
public ref class StringBuilder sealed : System::Runtime::Serialization::ISerializable
public sealed class StringBuilder
public sealed class StringBuilder : System.Runtime.Serialization.ISerializable
[System.Serializable]
public sealed class StringBuilder
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class StringBuilder : System.Runtime.Serialization.ISerializable
type StringBuilder = class
type StringBuilder = class
    interface ISerializable
[<System.Serializable>]
type StringBuilder = class
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type StringBuilder = class
    interface ISerializable
Public NotInheritable Class StringBuilder
Public NotInheritable Class StringBuilder
Implements ISerializable
Dědičnost
StringBuilder
Atributy
Implementuje

Příklady

Následující příklad ukazuje, jak volat mnoho metod definovaných StringBuilder třídou.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

Poznámky

Tato třída reprezentuje objekt typu řetězec, jehož hodnota je proměnlivá sekvence znaků.This class represents a string-like object whose value is a mutable sequence of characters.

V této části:In this section:

Typy String a StringBuilderThe String and StringBuilder types

I když StringBuilder a String obě představují sekvence znaků, jsou implementovány jinak.Although StringBuilder and String both represent sequences of characters, they are implemented differently. String je neměnný typ.String is an immutable type. To znamená, že každá operace, která se zobrazí pro úpravu String objektu, vytvoří nový řetězec.That is, each operation that appears to modify a String object actually creates a new string.

Například volání String.Concat metody v následujícím příkladu jazyka C# se zobrazí pro změnu hodnoty řetězcové proměnné s názvem 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. Ve skutečnosti Concat Metoda vrátí value objekt, který má jinou hodnotu a adresu z value objektu, který byl předán metodě.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. Všimněte si, že příklad musí být kompilován pomocí /unsafe Možnosti kompilátoru.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

Pro rutiny, které provádějí rozsáhlou manipulaci s řetězci (například aplikace, které mění řetězec několikrát ve smyčce), může se opakovaná úprava řetězce, která může přesně vypříčinit významné snížení výkonu.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. Alternativou je použití StringBuilder , což je proměnlivá řetězcová třída.The alternative is to use StringBuilder, which is a mutable string class. Proměnlivost znamená, že po vytvoření instance třídy je možné ji upravit připojením, odebráním, nahrazením nebo vložením znaků.Mutability means that once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters. StringBuilderObjekt udržuje vyrovnávací paměť pro přizpůsobení rozšíření řetězce.A StringBuilder object maintains a buffer to accommodate expansions to the string. Pokud je k dispozici místnost, připojí se k vyrovnávací paměti nová data; v opačném případě se přidělí nová, větší vyrovnávací paměť, data z původní vyrovnávací paměti se zkopírují do nové vyrovnávací paměti a nová data se pak připojí k nové vyrovnávací paměti.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.

Důležité

I když StringBuilder Třída všeobecně nabízí lepší výkon než String třída, neměli byste je automaticky nahrazovat vždy, když String StringBuilder chcete manipulovat s řetězci.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. Výkon závisí na velikosti řetězce, velikosti paměti, která má být přidělena novému řetězci, systému, ve kterém je aplikace spuštěná, a typu operace.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. Měli byste se připravit na testování vaší aplikace, abyste zjistili, jestli StringBuilder ve skutečnosti nabízí výrazné zlepšení výkonu.You should be prepared to test your app to determine whether StringBuilder actually offers a significant performance improvement.

Zvažte použití String třídy za těchto podmínek:Consider using the String class under these conditions:

  • V případě, že počet změn, které aplikace provede v řetězci, je malý.When the number of changes that your app will make to a string is small. V těchto případech se StringBuilder může nabízet zanedbatelné nebo žádné zvýšení výkonu String .In these cases, StringBuilder might offer negligible or no performance improvement over String.

  • Při provádění pevného počtu operací zřetězení, zejména u řetězcových literálů.When you are performing a fixed number of concatenation operations, particularly with string literals. V tomto případě může kompilátor kombinovat operace zřetězení do jediné operace.In this case, the compiler might combine the concatenation operations into a single operation.

  • V případě, že při sestavování řetězce budete muset provádět rozsáhlé operace hledání.When you have to perform extensive search operations while you are building your string. Ve StringBuilder třídě chybí metody vyhledávání, například IndexOf nebo StartsWith .The StringBuilder class lacks search methods such as IndexOf or StartsWith. Pro tyto operace budete muset převést StringBuilder objekt na a String a to může mít za to negaci výhod používání StringBuilder .You'll have to convert the StringBuilder object to a String for these operations, and this can negate the performance benefit from using StringBuilder. Další informace naleznete v části hledání textu v objektu StringBuilder .For more information, see the Searching the text in a StringBuilder object section.

Zvažte použití StringBuilder třídy za těchto podmínek:Consider using the StringBuilder class under these conditions:

  • Pokud očekáváte, že aplikace provede v době návrhu neznámý počet změn v řetězci (například při použití smyčky k zřetězení náhodného počtu řetězců, které obsahují vstup uživatele).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).

  • Pokud očekáváte, že aplikace provede významný počet změn v řetězci.When you expect your app to make a significant number of changes to a string.

Princip StringBuilderHow StringBuilder works

StringBuilder.LengthVlastnost označuje počet znaků, které StringBuilder objekt aktuálně obsahuje.The StringBuilder.Length property indicates the number of characters the StringBuilder object currently contains. Pokud přidáte znaky do StringBuilder objektu, jeho délka se zvyšuje, dokud se nerovná velikosti StringBuilder.Capacity vlastnosti, která definuje počet znaků, které může objekt obsahovat.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. Pokud počet přidaných znaků způsobí, že délka StringBuilder objektu překročí aktuální kapacitu, je přidělena nová paměť, hodnota Capacity vlastnosti je dvojitá, nové znaky jsou přidány do StringBuilder objektu a jeho Length vlastnost je upravena.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. Další paměť pro StringBuilder objekt je přidělována dynamicky, dokud nedosáhne hodnoty definované StringBuilder.MaxCapacity vlastností.Additional memory for the StringBuilder object is allocated dynamically until it reaches the value defined by the StringBuilder.MaxCapacity property. Po dosažení maximální kapacity nelze pro objekt přidělit žádná další paměť StringBuilder a pokus o přidání znaků nebo jejich rozšíření nad rámec maximální kapacity vyvolá ArgumentOutOfRangeException OutOfMemoryException výjimku nebo.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.

Následující příklad ukazuje, jak StringBuilder objekt přiděluje novou paměť a zvyšuje kapacitu dynamicky, protože řetězec přiřazený objektu se rozbalí.The following example illustrates how a StringBuilder object allocates new memory and increases its capacity dynamically as the string assigned to the object expands. Kód vytvoří StringBuilder objekt voláním jeho výchozího konstruktoru (bez parametrů).The code creates a StringBuilder object by calling its default (parameterless) constructor. Výchozí kapacita tohoto objektu je 16 znaků a jeho maximální kapacita je více než 2 000 000 000 znaků.The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters. Připojování řetězce "Toto je věta."Appending the string "This is a sentence." má za následek nové přidělení paměti, protože délka řetězce (19 znaků) překračuje výchozí kapacitu StringBuilder objektu.results in a new memory allocation because the string length (19 characters) exceeds the default capacity of the StringBuilder object. Kapacita objektu se zdvojnásobí na 32 znaků, přidá se nový řetězec a délka objektu se teď rovná 19 znaků.The capacity of the object doubles to 32 characters, the new string is added, and the length of the object now equals 19 characters. Kód pak připojí řetězec "Toto je další věta."The code then appends the string "This is an additional sentence." na hodnotu StringBuilder Object 11 krát.to the value of the StringBuilder object 11 times. Pokaždé, když operace přidávání způsobí, že délka StringBuilder objektu překročí kapacitu, je jeho stávající kapacita Dvojitá a Append operace bude úspěšná.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

Přidělení pamětiMemory allocation

Výchozí kapacita StringBuilder objektu je 16 znaků a jeho výchozí maximální kapacita je Int32.MaxValue .The default capacity of a StringBuilder object is 16 characters, and its default maximum capacity is Int32.MaxValue. Tyto výchozí hodnoty jsou použity, pokud zavoláte StringBuilder() StringBuilder(String) konstruktory a.These default values are used if you call the StringBuilder() and StringBuilder(String) constructors.

Můžete explicitně definovat počáteční kapacitu StringBuilder objektu následujícími způsoby:You can explicitly define the initial capacity of a StringBuilder object in the following ways:

  • Voláním jakéhokoli StringBuilder konstruktoru, který obsahuje capacity parametr při vytváření objektu.By calling any of the StringBuilder constructors that includes a capacity parameter when you create the object.

  • Tím, že explicitně přiřadíte novou hodnotu k StringBuilder.Capacity vlastnosti pro rozšíření existujícího StringBuilder objektu.By explicitly assigning a new value to the StringBuilder.Capacity property to expand an existing StringBuilder object. Všimněte si, že vlastnost vyvolá výjimku, pokud je nová kapacita menší než stávající kapacita nebo větší než StringBuilder Maximální kapacita objektu.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.

  • Voláním StringBuilder.EnsureCapacity metody s novou kapacitou.By calling the StringBuilder.EnsureCapacity method with the new capacity. Nová kapacita nesmí být větší než StringBuilder Maximální kapacita objektu.The new capacity must not be greater than the StringBuilder object's maximum capacity. Nicméně na rozdíl od přiřazení k Capacity vlastnosti EnsureCapacity nevyvolá výjimku, pokud je požadovaná nová kapacita menší než stávající kapacita; v tomto případě volání metody nemá žádný vliv.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.

Pokud délka řetězce přiřazeného StringBuilder objektu v volání konstruktoru přesáhne buď výchozí kapacitu, nebo zadanou kapacitu, Capacity vlastnost je nastavena na délku řetězce zadaného value parametrem.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.

Můžete explicitně definovat maximální kapacitu StringBuilder objektu voláním StringBuilder(Int32, Int32) konstruktoru.You can explicitly define the maximum capacity of a StringBuilder object by calling the StringBuilder(Int32, Int32) constructor. Maximální kapacitu nemůžete změnit přiřazením nové hodnoty k MaxCapacity vlastnosti, protože je jen pro čtení.You can't change the maximum capacity by assigning a new value to the MaxCapacity property, because it is read-only.

Jak ukazuje předchozí oddíl, pokaždé, když je stávající kapacita nedostatečná, je přidělena další paměť a kapacita StringBuilder objektu se zdvojnásobí na hodnotu definovanou MaxCapacity vlastností.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.

Obecně platí, že výchozí kapacita a maximální kapacita jsou dostačující pro většinu aplikací.In general, the default capacity and maximum capacity are adequate for most apps. Můžete zvážit nastavení těchto hodnot za následujících podmínek:You might consider setting these values under the following conditions:

  • Pokud je větší velikost StringBuilder objektu pravděpodobně větší než velká, většinou je překročena více megabajtů.If the eventual size of the StringBuilder object is likely to grow exceedingly large, typically in excess of several megabytes. V takovém případě může dojít k nějakému vlivu na výkon při nastavení počáteční Capacity vlastnosti na výrazně vysokou hodnotu, aby se eliminoval nutnost příliš velkého počtu realokaci paměti.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.

  • Pokud je vaše aplikace spuštěná v systému s omezeným množstvím paměti.If your app is running on a system with limited memory. V takovém případě můžete chtít zvážit nastavení MaxCapacity vlastnosti na méně Int32.MaxValue , než když vaše aplikace zpracovává velké řetězce, které by mohly způsobit jeho spuštění v paměťově omezeném prostředí.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.

Vytvoření instance objektu StringBuilderInstantiating a StringBuilder object

Vytvoříte instanci StringBuilder objektu voláním jednoho z jeho šesti přetížených konstruktorů třídy, které jsou uvedeny v následující tabulce.You instantiate a StringBuilder object by calling one of its six overloaded class constructors, which are listed in the following table. Tři konstruktory vytvoří instanci StringBuilder objektu, jehož hodnota je prázdný řetězec, ale nastavte Capacity MaxCapacity jiné hodnoty a.Three of the constructors instantiate a StringBuilder object whose value is an empty string, but set its Capacity and MaxCapacity values differently. Zbývající tři konstruktory definují StringBuilder objekt, který má konkrétní řetězcovou hodnotu a kapacitu.The remaining three constructors define a StringBuilder object that has a specific string value and capacity. Dva ze tří konstruktorů používají výchozí maximální kapacitu Int32.MaxValue , zatímco třetí umožňuje nastavit maximální kapacitu.Two of the three constructors use the default maximum capacity of Int32.MaxValue, whereas the third allows you to set the maximum capacity.

KonstruktorConstructor Řetězcová hodnotaString value KapacitaCapacity Maximální kapacitaMaximum capacity
StringBuilder() String.Empty 1616 Int32.MaxValue
StringBuilder(Int32) String.Empty Definováno capacity parametremDefined by the capacity parameter Int32.MaxValue
StringBuilder(Int32, Int32) String.Empty Definováno capacity parametremDefined by the capacity parameter Definováno maxCapacity parametremDefined by the maxCapacity parameter
StringBuilder(String) Definováno value parametremDefined by the value parameter 16 nebo value .16 or value. Length, podle toho, co je většíLength, whichever is greater Int32.MaxValue
StringBuilder(String, Int32) Definováno value parametremDefined by the value parameter Definováno capacity parametrem nebo value .Defined by the capacity parameter or value. Length, podle toho, co je větší.Length, whichever is greater. Int32.MaxValue
StringBuilder(String, Int32, Int32, Int32) Definováno value .Defined by value. Substring(startIndex, length)Substring(startIndex, length) Definováno capacity parametrem nebo value .Defined by the capacity parameter or value. Length, podle toho, co je větší.Length, whichever is greater. Int32.MaxValue

Následující příklad používá tři z těchto přetížení konstruktoru pro vytvoření instance StringBuilder objektů.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

Volání metod StringBuilderCalling StringBuilder methods

Většina metod, které upravují řetězec v StringBuilder instanci, vrací odkaz na stejnou instanci.Most of the methods that modify the string in a StringBuilder instance return a reference to that same instance. To umožňuje volat StringBuilder metody dvěma způsoby:This enables you to call StringBuilder methods in two ways:

  • Můžete provést jednotlivá volání metod a ignorovat návratovou hodnotu, jak je uvedeno v následujícím příkladu.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.
    
  • V jednom příkazu můžete vytvořit řadu volání metody.You can make a series of method calls in a single statement. To může být výhodné, pokud chcete napsat jediný příkaz, který řetězí po sobě jdoucích operací.This can be convenient if you want to write a single statement that chains successive operations. Následující příklad slučuje tři volání metod z předchozího příkladu do jediného řádku kódu.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.
    

Operace StringBuilderPerforming StringBuilder operations

Můžete použít metody StringBuilder třídy pro iteraci, přidání, odstranění nebo úpravu znaků v StringBuilder objektu.You can use the methods of the StringBuilder class to iterate, add, delete, or modify characters in a StringBuilder object.

Iterace znaků StringBuilderIterating StringBuilder characters

Ke znakům v objektu lze přistupovat StringBuilder pomocí StringBuilder.Chars[] Vlastnosti.You can access the characters in a StringBuilder object by using the StringBuilder.Chars[] property. V jazyce C# Chars[] je indexer; v Visual Basic je to výchozí vlastnost StringBuilder třídy.In C#, Chars[] is an indexer; in Visual Basic, it is the default property of the StringBuilder class. To umožňuje nastavit nebo načíst jednotlivé znaky pomocí jejich indexu, a to bez explicitního odkazování na Chars[] vlastnost.This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the Chars[] property. Znaky v StringBuilder objektu začínají na indexu 0 (nula) a pokračují v indexu Length -1.Characters in a StringBuilder object begin at index 0 (zero) and continue to index Length - 1.

Následující příklad ilustruje Chars[] vlastnost.The following example illustrates the Chars[] property. Připojí k objektu deset náhodných čísel StringBuilder a pak každý znak iterovat.It appends ten random numbers to a StringBuilder object, and then iterates each character. Pokud je kategorie Unicode znaku UnicodeCategory.DecimalDigitNumber , sníží se číslo o 1 (nebo se změní číslo na 9, pokud je jeho hodnota 0).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). V příkladu se zobrazí obsah StringBuilder objektu před i po změně hodnot jednotlivých znaků.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

Použití indexování pomocí znaků s Chars[] vlastností může být extrémně pomalé za následujících podmínek:Using character-based indexing with the Chars[] property can be extremely slow under the following conditions:

Výkon má vážně vliv, protože každý přístup k znaku projde celý propojený seznam bloků a najde správnou vyrovnávací paměť, do které se má indexovat.Performance is severely impacted because each character access walks the entire linked list of chunks to find the correct buffer to index into.

Poznámka

Dokonce i pro velký objekt "bloku" StringBuilder , který používá Chars[] vlastnost pro přístup na základě indexu k jednomu nebo malému počtu znaků, má zanedbatelný dopad na výkon; obvykle se jedná o operaci 0 (n) .Even for a large "chunky" StringBuilder object, using the Chars[] 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. Významný dopad na výkon nastane při iteraci znaků v StringBuilder objektu, což je operace o (n ^ 2) .The significant performance impact occurs when iterating the characters in the StringBuilder object, which is an O(n^2) operation.

Pokud narazíte na problémy s výkonem při použití indexování s StringBuilder objekty pomocí znaků, můžete použít kterékoli z následujících řešení:If you encounter performance issues when using character-based indexing with StringBuilder objects, you can use any of the following workarounds:

  • Převeďte StringBuilder instanci na a String tak, že zavoláte ToString metodu a pak získáte přístup ke znakům v řetězci.Convert the StringBuilder instance to a String by calling the ToString method, then access the characters in the string.

  • Zkopírujte obsah existujícího StringBuilder objektu do nového objektu, jehož velikost je předem nastavena StringBuilder .Copy the contents of the existing StringBuilder object to a new pre-sized StringBuilder object. Zvýšení výkonu se zlepší, protože nový objekt není v StringBuilder bloku dat.Performance improves because the new StringBuilder object is not chunky. Například: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)
    
  • Nastavte počáteční kapacitu StringBuilder objektu na hodnotu, která je přibližně rovna maximální očekávané velikosti voláním StringBuilder(Int32) konstruktoru.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. Všimněte si, že tato funkce přidělí celý blok paměti i v případě, že StringBuilder zřídka dosáhne své maximální kapacity.Note that this allocates the entire block of memory even if the StringBuilder rarely reaches its maximum capacity.

Přidání textu do objektu StringBuilderAdding text to a StringBuilder object

StringBuilderTřída obsahuje následující metody pro rozšíření obsahu StringBuilder objektu:The StringBuilder class includes the following methods for expanding the contents of a StringBuilder object:

  • AppendMetoda připojí řetězec, podřetězec, pole znaků, část pole znaků, jeden znak se opakuje několikrát nebo řetězcové vyjádření primitivního datového typu StringBuilder objektu.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.

  • AppendLineMetoda připojí ukončovací znak řádku nebo řetězec spolu s ukončovacím znakem řádku StringBuilder objektu.The AppendLine method appends a line terminator or a string along with a line terminator to a StringBuilder object.

  • AppendFormatMetoda připojí k objektu složený řetězec formátu StringBuilder .The AppendFormat method appends a composite format string to a StringBuilder object. Řetězcové reprezentace objektů zahrnutých ve výsledném řetězci mohou odrážet konvence formátování aktuální jazykové verze systému nebo zadané jazykové verze.The string representations of objects included in the result string can reflect the formatting conventions of the current system culture or a specified culture.

  • InsertMetoda vloží řetězec, podřetězec, více opakování řetězce, pole znaků, část pole znaků nebo řetězcové vyjádření primitivního datového typu na zadané pozici v StringBuilder objektu.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. Pozice je definována indexem založeným na nule.The position is defined by a zero-based index.

Následující příklad používá Append AppendLine metody,, a AppendFormat Insert k rozšíření textu StringBuilder objektu.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            <

Odstranění textu z objektu StringBuilderDeleting text from a StringBuilder object

StringBuilderTřída obsahuje metody, které mohou zmenšit velikost aktuální StringBuilder instance.The StringBuilder class includes methods that can reduce the size of the current StringBuilder instance. ClearMetoda odstraní všechny znaky a nastaví Length vlastnost na hodnotu nula.The Clear method removes all characters and sets the Length property to zero. RemoveMetoda odstraní zadaný počet znaků začínající na konkrétní pozici indexu.The Remove method deletes a specified number of characters starting at a particular index position. Kromě toho můžete odebrat znaky z konce StringBuilder objektu nastavením jeho Length vlastnosti na hodnotu, která je menší než délka aktuální instance.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.

Následující příklad odebere část textu z StringBuilder objektu, zobrazí jeho výslednou kapacitu, maximální kapacitu a délku hodnot vlastností a pak zavolá Clear metodu pro odebrání všech znaků z StringBuilder objektu.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

Úprava textu v objektu StringBuilderModifying the text in a StringBuilder object

StringBuilder.ReplaceMetoda nahradí všechny výskyty znaku nebo řetězce v celém StringBuilder objektu nebo v konkrétním rozsahu znaků.The StringBuilder.Replace method replaces all occurrences of a character or a string in the entire StringBuilder object or in a particular character range. Následující příklad používá Replace metodu k nahrazení všech bodů vykřičník (!) otazníky (?) v StringBuilder objektu.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?

Hledání textu v objektu StringBuilderSearching the text in a StringBuilder object

StringBuilderTřída nezahrnuje metody String.Contains , které jsou podobné metodám, String.IndexOf a String.StartsWith poskytované String třídou, což umožňuje vyhledat objekt pro konkrétní znak nebo podřetězec.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. Určení přítomnosti nebo počáteční pozice znaku podřetězce vyžaduje, abyste prohledali String hodnotu pomocí metody vyhledávání řetězců nebo regulárního výrazu.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. Existují čtyři způsoby implementace takového hledání, jak je uvedeno v následující tabulce.There are four ways to implement such searches, as the following table shows.

TechnikaTechnique VýhodyPros NevýhodyCons
Hledané hodnoty řetězce před jejich přidáním do StringBuilder objektu.Search string values before adding them to the StringBuilder object. Užitečné pro zjištění, zda existuje dílčí řetězec.Useful for determining whether a substring exists. Nelze ji použít, je-li důležité umístění indexu podřetězce.Cannot be used when the index position of a substring is important.
Volání ToString a hledání vráceného String objektu.Call ToString and search the returned String object. Snadné použití, pokud přiřadíte veškerý text k StringBuilder objektu a pak ho začnete upravovat.Easy to use if you assign all the text to a StringBuilder object, and then begin to modify it. Nenáročný k opakovanému volání, ToString Pokud je nutné provést úpravy před přidáním textu do StringBuilder objektu.Cumbersome to repeatedly call ToString if you must make modifications before all text is added to the StringBuilder object.

Pokud provádíte změny, musíte si pamatovat, že budete pracovat na konci StringBuilder textu objektu.You must remember to work from the end of the StringBuilder object's text if you're making changes.
Vlastnost slouží Chars[] k sekvenčnímu vyhledávání rozsahu znaků.Use the Chars[] property to sequentially search a range of characters. Užitečné v případě, že máte obavy s jednotlivými znaky nebo malým podřetězcem.Useful if you're concerned with individual characters or a small substring. Nenáročný, pokud je počet znaků, který se má hledat, velký, nebo pokud je logika hledání složitá.Cumbersome if the number of characters to search is large or if the search logic is complex.

Výsledkem je velmi špatný výkon pro objekty, které jsou velmi velké prostřednictvím opakované volání metody.Results in very poor performance for objects that have grown very large through repeated method calls.
Převeďte StringBuilder objekt na String objekt a proveďte úpravy String objektu.Convert the StringBuilder object to a String object, and perform modifications on the String object. Užitečné, pokud je počet úprav malý.Useful if the number of modifications is small. Negace výhod výkonu StringBuilder třídy, pokud je počet úprav velký.Negates the performance benefit of the StringBuilder class if the number of modifications is large.

Pojďme tyto techniky podrobněji prošetřit.Let's examine these techniques in greater detail.

  • Pokud je cílem hledání určit, zda určitý podřetězec existuje (tj. Pokud se nechcete zajímat o pozici podřetězce), můžete hledat řetězce před jejich uložením v StringBuilder objektu.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. Následující příklad poskytuje jednu možnou implementaci.The following example provides one possible implementation. Definuje třídu, StringBuilderFinder jejíž konstruktor je předán odkaz na StringBuilder objekt a dílčí řetězec, který se má najít v řetězci.It defines a StringBuilderFinder class whose constructor is passed a reference to a StringBuilder object and the substring to find in the string. V tomto případě se v příkladu pokusí určit, zda jsou zaznamenané teploty ve stupních Fahrenheita nebo stupních Celsia, a přidá příslušný úvodní text na začátek StringBuilder objektu.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. Generátor náhodných čísel slouží k výběru pole, které obsahuje data ve stupních Celsia nebo stupních Fahrenheita.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
    
  • Zavolejte StringBuilder.ToString metodu pro převedení StringBuilder objektu na String objekt.Call the StringBuilder.ToString method to convert the StringBuilder object to a String object. Řetězec můžete hledat pomocí metod, jako je String.LastIndexOf nebo String.StartsWith , nebo můžete použít regulární výrazy a Regex třídu pro hledání vzorů.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. Vzhledem k tomu, že oba StringBuilder String objekty a používají pro ukládání znaků kódování UTF-16, jsou pozice indexů znaků, podřetězců a regulárních výrazů stejné v obou objektech.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. To umožňuje použít StringBuilder metody k provedení změn ve stejné pozici, ve které je tento text nalezen v String objektu.This enables you to use StringBuilder methods to make changes at the same position at which that text is found in the String object.

    Poznámka

    Pokud jste tento přístup přijali, měli byste pracovat na konci StringBuilder objektu na jeho začátek, takže nemusíte znovu převádět StringBuilder objekt na řetězec.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.

    Tento postup znázorňuje následující příklad.The following example illustrates this approach. Ukládá čtyři výskyty každého písmena anglické abecedy v StringBuilder objektu.It stores four occurrences of each letter of the English alphabet in a StringBuilder object. Pak převede text na String objekt a pomocí regulárního výrazu identifikuje počáteční pozici každé čtyři znakové sekvence.It then converts the text to a String object and uses a regular expression to identify the starting position of each four-character sequence. Nakonec přidá podtržítko před každou sekvenci čtyř znaků s výjimkou první sekvence a převede první znak sekvence na velká písmena.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
    
  • Vlastnost slouží StringBuilder.Chars[] k sekvenčnímu vyhledávání rozsahu znaků v StringBuilder objektu.Use the StringBuilder.Chars[] property to sequentially search a range of characters in a StringBuilder object. Tento přístup nemusí být praktický, pokud je počet prohledávaných znaků velký nebo je logika hledání zvláště složitá.This approach may not be practical if the number of characters to be searched is large or the search logic is particularly complex. Dopad přístupu na základě indexu typu znak po znaku pro velmi velké objekty v bloku dat StringBuilder naleznete v dokumentaci k StringBuilder.Chars[] Vlastnosti.For the performance implications of character-by-character index-based access for very large, chunked StringBuilder objects, see the documentation for the StringBuilder.Chars[] property.

    Následující příklad je stejný v funkčnosti jako v předchozím příkladu, ale liší se v implementaci.The following example is identical in functionality to the previous example but differs in implementation. Používá Chars[] vlastnost k detekci, kdy se hodnota znaku změnila, vloží podtržítko na tuto pozici a převede první znak v nové sekvenci na velká písmena.It uses the Chars[] 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
    
  • Uložte všechen neupravený text do StringBuilder objektu, zavolejte StringBuilder.ToString metodu pro převod StringBuilder objektu na String objekt a proveďte úpravy String objektu.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. Tento postup můžete použít, pokud máte pouze několik úprav. v opačném případě náklady na práci s neproměnlivými řetězci mohou mít za vliv na výkon použití objektu negaci výhod 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.

    Následující příklad je stejný jako ve funkci v předchozích dvou příkladech, ale liší se v implementaci.The following example is identical in functionality to the previous two examples but differs in implementation. Vytvoří StringBuilder objekt, převede jej na String objekt a poté použije regulární výraz k provedení všech zbývajících úprav v řetězci.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)Metoda používá výraz lambda k provedení náhrady při každé shodě.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
    

Převod objektu StringBuilder na řetězecConverting the StringBuilder object to a string

Objekt je nutné převést StringBuilder na String objekt před předáním řetězce reprezentovaného StringBuilder objektem metodě, která má String parametr nebo jej zobrazit v uživatelském rozhraní.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. Tento převod provedete voláním StringBuilder.ToString metody.You perform this conversion by calling the StringBuilder.ToString method. Ilustrace naleznete v předchozím příkladu, který volá ToString metodu pro převod StringBuilder objektu na řetězec, aby jej bylo možné předat metodě regulárního výrazu.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.

Poznámky pro volající

V rozhraní .NET Core a v .NET Framework 4,0 a novějších verzích při vytváření instance StringBuilder objektu voláním StringBuilder(Int32, Int32) konstruktoru může být délka i kapacita StringBuilder instance větší než hodnota jeho MaxCapacity Vlastnosti.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. K tomu může dojít zejména při volání Append(String) metod a AppendFormat(String, Object) pro připojení malých řetězců.This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.

Konstruktory

StringBuilder()

Inicializuje novou instanci StringBuilder třídy.Initializes a new instance of the StringBuilder class.

StringBuilder(Int32)

Inicializuje novou instanci StringBuilder třídy pomocí zadané kapacity.Initializes a new instance of the StringBuilder class using the specified capacity.

StringBuilder(Int32, Int32)

Inicializuje novou instanci StringBuilder třídy, která začíná zadanou kapacitou a může růst na zadané maximum.Initializes a new instance of the StringBuilder class that starts with a specified capacity and can grow to a specified maximum.

StringBuilder(String)

Inicializuje novou instanci StringBuilder třídy pomocí zadaného řetězce.Initializes a new instance of the StringBuilder class using the specified string.

StringBuilder(String, Int32)

Inicializuje novou instanci StringBuilder třídy pomocí zadaného řetězce a kapacity.Initializes a new instance of the StringBuilder class using the specified string and capacity.

StringBuilder(String, Int32, Int32, Int32)

Inicializuje novou instanci StringBuilder třídy ze zadaného podřetězce a kapacity.Initializes a new instance of the StringBuilder class from the specified substring and capacity.

Vlastnosti

Capacity

Získá nebo nastaví maximální počet znaků, které mohou být obsaženy v paměti přidělené aktuální instancí.Gets or sets the maximum number of characters that can be contained in the memory allocated by the current instance.

Chars[Int32]

Získá nebo nastaví znak na pozici zadaného znaku v této instanci.Gets or sets the character at the specified character position in this instance.

Length

Získá nebo nastaví délku aktuálního StringBuilder objektu.Gets or sets the length of the current StringBuilder object.

MaxCapacity

Získá maximální kapacitu této instance.Gets the maximum capacity of this instance.

Metody

Append(Boolean)

Připojí řetězcovou reprezentaci zadané logické hodnoty k této instanci.Appends the string representation of a specified Boolean value to this instance.

Append(Byte)

Připojí řetězcovou reprezentaci zadaného 8 bitové unsigned integer k této instanci.Appends the string representation of a specified 8-bit unsigned integer to this instance.

Append(Char)

Připojí řetězcovou reprezentaci zadaného Char objektu k této instanci.Appends the string representation of a specified Char object to this instance.

Append(Char*, Int32)

Připojí pole znaků Unicode počínaje zadanou adresou k této instanci.Appends an array of Unicode characters starting at a specified address to this instance.

Append(Char, Int32)

Připojí zadaný počet kopií řetězcové reprezentace znaku Unicode k této instanci.Appends a specified number of copies of the string representation of a Unicode character to this instance.

Append(Char[])

Připojí řetězcovou reprezentaci znaků Unicode v zadaném poli do této instance.Appends the string representation of the Unicode characters in a specified array to this instance.

Append(Char[], Int32, Int32)

Připojí řetězcovou reprezentaci zadaného podpole znaků Unicode k této instanci.Appends the string representation of a specified subarray of Unicode characters to this instance.

Append(Decimal)

Připojí řetězcovou reprezentaci zadaného desítkového čísla k této instanci.Appends the string representation of a specified decimal number to this instance.

Append(Double)

Připojí řetězcovou reprezentaci zadaného čísla s plovoucí desetinnou čárkou s dvojitou přesností k této instanci.Appends the string representation of a specified double-precision floating-point number to this instance.

Append(Int16)

Připojí řetězcovou reprezentaci zadaného 16bitového podepsaného typu Integer k této instanci.Appends the string representation of a specified 16-bit signed integer to this instance.

Append(Int32)

Připojí k této instanci řetězcové vyjádření zadaného celého čísla se znaménkem 32.Appends the string representation of a specified 32-bit signed integer to this instance.

Append(Int64)

Připojí k této instanci řetězcové vyjádření zadaného celého čísla se znaménkem 64.Appends the string representation of a specified 64-bit signed integer to this instance.

Append(Object)

Připojí řetězcovou reprezentaci zadaného objektu k této instanci.Appends the string representation of a specified object to this instance.

Append(ReadOnlyMemory<Char>)

Připojí řetězcovou reprezentaci zadané oblasti paměťových znaků jen pro čtení k této instanci.Appends the string representation of a specified read-only character memory region to this instance.

Append(ReadOnlySpan<Char>)

Připojí řetězcovou reprezentaci zadaného znakového rozsahu jen pro čtení k této instanci.Appends the string representation of a specified read-only character span to this instance.

Append(SByte)

Připojí řetězcovou reprezentaci zadaného 8bitového čísla se znaménkem do této instance.Appends the string representation of a specified 8-bit signed integer to this instance.

Append(Single)

Připojí řetězcovou reprezentaci zadaného čísla s plovoucí desetinnou čárkou s jednoduchou přesností k této instanci.Appends the string representation of a specified single-precision floating-point number to this instance.

Append(String)

Připojí kopii zadaného řetězce k této instanci.Appends a copy of the specified string to this instance.

Append(String, Int32, Int32)

Připojí kopii zadaného podřetězce k této instanci.Appends a copy of a specified substring to this instance.

Append(StringBuilder)

Připojí řetězcovou reprezentaci zadaného tvůrce řetězců k této instanci.Appends the string representation of a specified string builder to this instance.

Append(StringBuilder, Int32, Int32)

Připojí kopii podřetězce v rámci zadaného tvůrce řetězce k této instanci.Appends a copy of a substring within a specified string builder to this instance.

Append(UInt16)

Připojí řetězcovou reprezentaci zadaného 16bitového unsigned integer do této instance.Appends the string representation of a specified 16-bit unsigned integer to this instance.

Append(UInt32)

Připojí řetězcovou reprezentaci zadaného 32 bitové unsigned integer k této instanci.Appends the string representation of a specified 32-bit unsigned integer to this instance.

Append(UInt64)

Připojí řetězcovou reprezentaci zadaného 64 bitové unsigned integer k této instanci.Appends the string representation of a specified 64-bit unsigned integer to this instance.

AppendFormat(IFormatProvider, String, Object)

Připojí řetězec vrácený zpracováním složeného formátovacího řetězce, který v této instanci obsahuje nula nebo více položek formátu.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Každá položka formátu je nahrazena řetězcovou reprezentací jediného argumentu pomocí zadaného poskytovatele formátu.Each format item is replaced by the string representation of a single argument using a specified format provider.

AppendFormat(IFormatProvider, String, Object, Object)

Připojí řetězec vrácený zpracováním složeného formátovacího řetězce, který v této instanci obsahuje nula nebo více položek formátu.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Každá položka formátu je nahrazena řetězcovou reprezentací některého ze dvou argumentů pomocí zadaného poskytovatele formátu.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)

Připojí řetězec vrácený zpracováním složeného formátovacího řetězce, který v této instanci obsahuje nula nebo více položek formátu.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Každá položka formátu je nahrazena řetězcovou reprezentací jednoho ze tří argumentů pomocí zadaného poskytovatele formátu.Each format item is replaced by the string representation of either of three arguments using a specified format provider.

AppendFormat(IFormatProvider, String, Object[])

Připojí řetězec vrácený zpracováním složeného formátovacího řetězce, který v této instanci obsahuje nula nebo více položek formátu.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Každá položka formátu je nahrazena řetězcovou reprezentací odpovídajícího argumentu v poli parametrů pomocí zadaného poskytovatele formátu.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)

Připojí řetězec vrácený zpracováním složeného formátovacího řetězce, který v této instanci obsahuje nula nebo více položek formátu.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Každá položka formátu je nahrazena řetězcovou reprezentací jediného argumentu.Each format item is replaced by the string representation of a single argument.

AppendFormat(String, Object, Object)

Připojí řetězec vrácený zpracováním složeného formátovacího řetězce, který v této instanci obsahuje nula nebo více položek formátu.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Každá položka formátu je nahrazena řetězcovou reprezentací některého ze dvou argumentů.Each format item is replaced by the string representation of either of two arguments.

AppendFormat(String, Object, Object, Object)

Připojí řetězec vrácený zpracováním složeného formátovacího řetězce, který v této instanci obsahuje nula nebo více položek formátu.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Každá položka formátu je nahrazena řetězcovou reprezentací jednoho ze tří argumentů.Each format item is replaced by the string representation of either of three arguments.

AppendFormat(String, Object[])

Připojí řetězec vrácený zpracováním složeného formátovacího řetězce, který v této instanci obsahuje nula nebo více položek formátu.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Každá položka formátu je nahrazena řetězcovou reprezentací odpovídajícího argumentu v poli parametrů.Each format item is replaced by the string representation of a corresponding argument in a parameter array.

AppendJoin(Char, Object[])

Zřetězí řetězcové reprezentace prvků v zadaném poli objektů pomocí zadaného oddělovače znaků mezi každým členem a pak připojí výsledek k aktuální instanci tvůrce řetězců.Concatenates the string representations of the elements in the provided array of objects, using the specified char separator between each member, then appends the result to the current instance of the string builder.

AppendJoin(Char, String[])

Zřetězí řetězce zadaného pole pomocí zadaného oddělovače znaků mezi každým řetězcem a pak připojí výsledek k aktuální instanci tvůrce řetězců.Concatenates the strings of the provided array, using the specified char separator between each string, then appends the result to the current instance of the string builder.

AppendJoin(String, Object[])

Zřetězí řetězcové reprezentace prvků v zadaném poli objektů pomocí zadaného oddělovače mezi každým členem a pak připojí výsledek k aktuální instanci tvůrce řetězců.Concatenates the string representations of the elements in the provided array of objects, using the specified separator between each member, then appends the result to the current instance of the string builder.

AppendJoin(String, String[])

Zřetězí řetězce zadaného pole pomocí zadaného oddělovače mezi každým řetězcem a pak připojí výsledek k aktuální instanci tvůrce řetězců.Concatenates the strings of the provided array, using the specified separator between each string, then appends the result to the current instance of the string builder.

AppendJoin<T>(Char, IEnumerable<T>)

Zřetězí a připojí členy kolekce pomocí zadaného oddělovače znaků mezi každým členem.Concatenates and appends the members of a collection, using the specified char separator between each member.

AppendJoin<T>(String, IEnumerable<T>)

Zřetězí a připojí členy kolekce pomocí zadaného oddělovače mezi jednotlivými členy.Concatenates and appends the members of a collection, using the specified separator between each member.

AppendLine()

Připojí výchozí ukončovací znak řádku na konec aktuálního StringBuilder objektu.Appends the default line terminator to the end of the current StringBuilder object.

AppendLine(String)

Připojí kopii zadaného řetězce následovaného výchozím zakončením řádku na konci aktuálního StringBuilder objektu.Appends a copy of the specified string followed by the default line terminator to the end of the current StringBuilder object.

Clear()

Odebere všechny znaky z aktuální StringBuilder instance.Removes all characters from the current StringBuilder instance.

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

Zkopíruje znaky ze zadaného segmentu této instance do zadaného segmentu cílového Char pole.Copies the characters from a specified segment of this instance to a specified segment of a destination Char array.

CopyTo(Int32, Span<Char>, Int32)

Zkopíruje znaky ze zadaného segmentu této instance do cílového Char rozpětí.Copies the characters from a specified segment of this instance to a destination Char span.

EnsureCapacity(Int32)

Zajistí, aby kapacita této instance StringBuilder byla aspoň zadaná hodnota.Ensures that the capacity of this instance of StringBuilder is at least the specified value.

Equals(Object)

Určí, zda se zadaný objekt rovná aktuálnímu objektu.Determines whether the specified object is equal to the current object.

(Zděděno od Object)
Equals(ReadOnlySpan<Char>)

Vrátí hodnotu, která označuje, zda jsou znaky v této instanci rovny znakům v zadaném rozsahu znaků jen pro čtení.Returns a value indicating whether the characters in this instance are equal to the characters in a specified read-only character span.

Equals(StringBuilder)

Vrací hodnotu, která určuje, zda je tato instance rovna zadanému objektu.Returns a value indicating whether this instance is equal to a specified object.

GetChunks()

Vrátí objekt, který lze použít k iteraci v blocích znaků reprezentovaných ReadOnlyMemory<Char> z této StringBuilder instance.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()

Slouží jako výchozí funkce hash.Serves as the default hash function.

(Zděděno od Object)
GetType()

Získá Type aktuální instanci.Gets the Type of the current instance.

(Zděděno od Object)
Insert(Int32, Boolean)

Vloží řetězcovou reprezentaci logické hodnoty do této instance na zadané pozici znaku.Inserts the string representation of a Boolean value into this instance at the specified character position.

Insert(Int32, Byte)

Vloží řetězcovou reprezentaci zadaného 8 bitové unsigned integer do této instance na zadané pozici znaku.Inserts the string representation of a specified 8-bit unsigned integer into this instance at the specified character position.

Insert(Int32, Char)

Vloží řetězcovou reprezentaci zadaného znaku Unicode do této instance v zadané pozici znaku.Inserts the string representation of a specified Unicode character into this instance at the specified character position.

Insert(Int32, Char[])

Vloží řetězcovou reprezentaci zadaného pole znaků Unicode do této instance v zadané pozici znaku.Inserts the string representation of a specified array of Unicode characters into this instance at the specified character position.

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

Vloží řetězcovou reprezentaci zadaného podpole znaků Unicode do této instance na zadané pozici znaku.Inserts the string representation of a specified subarray of Unicode characters into this instance at the specified character position.

Insert(Int32, Decimal)

Vloží řetězcovou reprezentaci desítkového čísla do této instance na zadané pozici znaku.Inserts the string representation of a decimal number into this instance at the specified character position.

Insert(Int32, Double)

Vloží řetězcovou reprezentaci čísla s plovoucí desetinnou čárkou s dvojitou přesností do této instance v zadané pozici znaku.Inserts the string representation of a double-precision floating-point number into this instance at the specified character position.

Insert(Int32, Int16)

Vloží řetězcové vyjádření zadaného 16bitového celého čísla se znaménkem do této instance na zadané pozici znaku.Inserts the string representation of a specified 16-bit signed integer into this instance at the specified character position.

Insert(Int32, Int32)

Vloží řetězcovou reprezentaci zadaného celého čísla se znaménkem (32) do této instance na zadané pozici znaku.Inserts the string representation of a specified 32-bit signed integer into this instance at the specified character position.

Insert(Int32, Int64)

Vloží řetězcovou reprezentaci 64ého celého čísla se znaménkem do této instance na zadané pozici znaku.Inserts the string representation of a 64-bit signed integer into this instance at the specified character position.

Insert(Int32, Object)

Vloží řetězcovou reprezentaci objektu do této instance v zadané pozici znaku.Inserts the string representation of an object into this instance at the specified character position.

Insert(Int32, ReadOnlySpan<Char>)

Vloží sekvenci znaků do této instance v zadané pozici znaku.Inserts the sequence of characters into this instance at the specified character position.

Insert(Int32, SByte)

Vloží řetězcovou reprezentaci zadaného 8bitového čísla se znaménkem do této instance na zadané pozici znaku.Inserts the string representation of a specified 8-bit signed integer into this instance at the specified character position.

Insert(Int32, Single)

Vloží řetězcové vyjádření čísla s plovoucí desetinnou čárkou s jednoduchou přesností do této instance na zadané pozici znaku.Inserts the string representation of a single-precision floating point number into this instance at the specified character position.

Insert(Int32, String)

Vloží řetězec do této instance na zadané pozici znaku.Inserts a string into this instance at the specified character position.

Insert(Int32, String, Int32)

Vloží jednu nebo více kopií zadaného řetězce do této instance v zadané pozici znaku.Inserts one or more copies of a specified string into this instance at the specified character position.

Insert(Int32, UInt16)

Vloží řetězcovou reprezentaci 16bitového unsigned integer do této instance v zadané pozici znaku.Inserts the string representation of a 16-bit unsigned integer into this instance at the specified character position.

Insert(Int32, UInt32)

Vloží řetězcovou reprezentaci 32 unsigned integer do této instance na zadané pozici znaku.Inserts the string representation of a 32-bit unsigned integer into this instance at the specified character position.

Insert(Int32, UInt64)

Vloží řetězcovou reprezentaci 64 unsigned integer do této instance na zadané pozici znaku.Inserts the string representation of a 64-bit unsigned integer into this instance at the specified character position.

MemberwiseClone()

Vytvoří kopii aktuálního seznamu Object .Creates a shallow copy of the current Object.

(Zděděno od Object)
Remove(Int32, Int32)

Odebere zadaný rozsah znaků z této instance.Removes the specified range of characters from this instance.

Replace(Char, Char)

Nahradí všechny výskyty zadaného znaku v této instanci jiným zadaným znakem.Replaces all occurrences of a specified character in this instance with another specified character.

Replace(Char, Char, Int32, Int32)

Nahradí v rámci podřetězce této instance všechny výskyty zadaného znaku jiným zadaným znakem.Replaces, within a substring of this instance, all occurrences of a specified character with another specified character.

Replace(String, String)

Nahradí všechny výskyty zadaného řetězce v této instanci jiným zadaným řetězcem.Replaces all occurrences of a specified string in this instance with another specified string.

Replace(String, String, Int32, Int32)

Nahradí v rámci podřetězce této instance všechny výskyty zadaného řetězce s jiným zadaným řetězcem.Replaces, within a substring of this instance, all occurrences of a specified string with another specified string.

ToString()

Převede hodnotu této instance na String .Converts the value of this instance to a String.

ToString(Int32, Int32)

Převede hodnotu podřetězce této instance na String .Converts the value of a substring of this instance to a String.

Explicitní implementace rozhraní

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Naplní SerializationInfo objekt daty potřebnými k deserializaci aktuálního StringBuilder objektu.Populates a SerializationInfo object with the data necessary to deserialize the current StringBuilder object.

Platí pro

Viz také