StringBuilder Sınıf

Tanım

Kesilebilir bir karakter dizesini temsil eder.Represents a mutable string of characters. Bu sınıf devralınamaz.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
Devralma
StringBuilder
Öznitelikler
Uygulamalar

Örnekler

Aşağıdaki örnek, sınıfı tarafından tanımlanan birçok yöntemin nasıl çağrılacağını gösterir StringBuilder .The following example shows how to call many of the methods defined by the StringBuilder class.

using namespace System;
using namespace System::Text;

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

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

    // Append a format string to the end of the StringBuilder.
    sb->AppendFormat("GHI{0}{1}", (Char)'J', (Char)'k');

    // Display the number of characters in the StringBuilder
    // and its string.
    Console::WriteLine("{0} chars: {1}", sb->Length, sb->ToString());

    // Insert a string at the beginning of the StringBuilder.
    sb->Insert(0, "Alphabet: ");

    // Replace all lowercase k's with uppercase K's.
    sb->Replace('k', 'K');

    // Display the number of characters in the StringBuilder
    // and its string.
    Console::WriteLine("{0} chars: {1}", sb->Length, sb->ToString());
}

// This code produces the following output.
//
// 11 chars: ABCDEFGHIJk
// 21 chars: Alphabet: ABCDEFGHIJK
using System;
using System.Text;

public sealed class App
{
    static void Main()
    {
        // Create a StringBuilder that expects to hold 50 characters.
        // Initialize the StringBuilder with "ABC".
        StringBuilder sb = new StringBuilder("ABC", 50);

        // Append three characters (D, E, and F) to the end of the StringBuilder.
        sb.Append(new char[] { 'D', 'E', 'F' });

        // Append a format string to the end of the StringBuilder.
        sb.AppendFormat("GHI{0}{1}", 'J', 'k');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());

        // Insert a string at the beginning of the StringBuilder.
        sb.Insert(0, "Alphabet: ");

        // Replace all lowercase k's with uppercase K's.
        sb.Replace('k', 'K');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());
    }
}

// This code produces the following output.
//
// 11 chars: ABCDEFGHIJk
// 21 chars: Alphabet: ABCDEFGHIJK
Imports System.Text

Public Module App 
    Public Sub Main() 
        ' Create a StringBuilder that expects to hold 50 characters.
        ' Initialize the StringBuilder with "ABC".
        Dim sb As New StringBuilder("ABC", 50)

        ' Append three characters (D, E, and F) to the end of the StringBuilder.
        sb.Append(New Char() {"D"c, "E"c, "F"c})

        ' Append a format string to the end of the StringBuilder.
        sb.AppendFormat("GHI{0}{1}", "J"c, "k"c)

        ' Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString())

        ' Insert a string at the beginning of the StringBuilder.
        sb.Insert(0, "Alphabet: ")

        ' Replace all lowercase k's with uppercase K's.
        sb.Replace("k", "K")

        ' Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString())
    End Sub
End Module

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

Açıklamalar

Bu sınıf, değeri kesilebilir karakter dizisi olan dize benzeri bir nesneyi temsil eder.This class represents a string-like object whose value is a mutable sequence of characters.

Bu bölümdeki konular:In this section:

Dize ve StringBuilder türleriThe String and StringBuilder types

StringBuilder String Her ikisi de karakter dizilerini temsil etse de farklı şekilde uygulanır.Although StringBuilder and String both represent sequences of characters, they are implemented differently. String sabit bir türdür.String is an immutable type. Diğer bir deyişle, bir nesneyi değiştirmek için görünen her işlem, String aslında yeni bir dize oluşturur.That is, each operation that appears to modify a String object actually creates a new string.

Örneğin, String.Concat Aşağıdaki C# örneğinde yöntemine yapılan çağrı, adlı bir dize değişkeninin değerini değiştirecek şekilde görünür 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. Aslında, Concat yöntemi value yöntemine geçirilen nesneden farklı bir değere ve adrese sahip bir nesne döndürür value .In fact, the Concat method returns a value object that has a different value and address from the value object that was passed to the method. Örneğin, derleyici seçeneği kullanılarak derlenmesi gerektiğini unutmayın /unsafe .Note that the example must be compiled using the /unsafe compiler option.

using System;

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

Kapsamlı dize düzenlemesi gerçekleştiren yordamlar (bir dizeyi bir döngüde çok sayıda değiştiren uygulamalar gibi) için, dizeyi tekrar tekrar değiştirmek, önemli bir performans cezası ile tam olarak yapılabilir.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. Alternatif, StringBuilder değişebilir bir dize sınıfı olan kullanmaktır.The alternative is to use StringBuilder, which is a mutable string class. Değiştirici, sınıfın bir örneği oluşturulduktan sonra karakter ekleyerek, kaldırarak, değiştirilerek veya ekleyerek değiştirilebilen anlamına gelir.Mutability means that once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters. StringBuilderNesnesi, dizeye yönelik genişleimler sağlamak için bir arabellek tutar.A StringBuilder object maintains a buffer to accommodate expansions to the string. Yer varsa, yeni veriler arabelleğe eklenir; Aksi takdirde, yeni, daha büyük bir arabellek ayrılır, özgün arabelleğin verileri yeni arabelleğe kopyalanır ve yeni veriler yeni arabelleğin sonuna eklenir.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.

Önemli

StringBuilderSınıfı genellikle sınıftan daha iyi performans sunmakla birlikte String , String dizeleri her işlemek istediğiniz zaman otomatik olarak ' i değiştirmelisiniz StringBuilder .Although the StringBuilder class generally offers better performance than the String class, you should not automatically replace String with StringBuilder whenever you want to manipulate strings. Performans, dizenin boyutuna, yeni dize için ayrılacak bellek miktarına, uygulamanızın yürütüldüğü sisteme ve işlem türüne bağlıdır.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. Uygulamanızı test etmek için hazırlıklı olmanız gerekir. Bu, StringBuilder gerçek anlamda önemli bir performans artışı sağlar.You should be prepared to test your app to determine whether StringBuilder actually offers a significant performance improvement.

StringAşağıdaki koşullarda sınıfını kullanmayı düşünün:Consider using the String class under these conditions:

  • Uygulamanızın bir dizeye yapması için gereken değişiklik sayısı küçük.When the number of changes that your app will make to a string is small. Bu durumlarda, StringBuilder aşırı göz ardı edilebilir veya hiç performans artışı sağlayabilir String .In these cases, StringBuilder might offer negligible or no performance improvement over String.

  • Sabit sayıda birleştirme işlemini gerçekleştirirken, özellikle dize değişmez değerleri ile.When you are performing a fixed number of concatenation operations, particularly with string literals. Bu durumda, derleyici birleştirme işlemlerini tek bir işlem halinde birleştirebilir.In this case, the compiler might combine the concatenation operations into a single operation.

  • Dizenizi oluştururken kapsamlı arama işlemleri gerçekleştirmeniz gerekir.When you have to perform extensive search operations while you are building your string. StringBuilderSınıfta veya gibi arama yöntemleri eksiktir IndexOf StartsWith .The StringBuilder class lacks search methods such as IndexOf or StartsWith. Bu StringBuilder işlemler için nesnesini bir öğesine dönüştürmeniz gerekir String ve bu işlem, performans avantajını kullanarak bu işlemi gerçekleştirebilir 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. Daha fazla bilgi için bkz. bir StringBuilder nesnesi içinde metni arama .For more information, see the Searching the text in a StringBuilder object section.

StringBuilderAşağıdaki koşullarda sınıfını kullanmayı düşünün:Consider using the StringBuilder class under these conditions:

  • Uygulamanızın tasarım zamanında bir dizede bilinmeyen sayıda değişiklik yapmasını beklediğinizi (örneğin, Kullanıcı girişi içeren rastgele sayıda dizeyi birleştirmek için bir döngü kullanırken).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).

  • Uygulamanızı bir dizede önemli sayıda değişiklik yapmak için bekliyor.When you expect your app to make a significant number of changes to a string.

StringBuilder nasıl çalışır?How StringBuilder works

StringBuilder.LengthÖzelliği StringBuilder nesnenin şu anda içerdiği karakter sayısını gösterir.The StringBuilder.Length property indicates the number of characters the StringBuilder object currently contains. Nesnesine karakter eklerseniz StringBuilder , bu nesnenin uzunluğu özelliğin boyutuna eşit olana kadar artar, bu da StringBuilder.Capacity nesnenin içerebileceği karakter sayısını tanımlar.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. Eklenen karakterlerin sayısı StringBuilder nesnenin uzunluğunun geçerli kapasitesini aşmasına neden olursa, yeni bellek ayrılır, Capacity özelliğin değeri iki katına çıkarılır, yeni karakterler StringBuilder nesneye eklenir ve Length özelliği ayarlanır.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. Nesnenin ek belleği, StringBuilder özelliği tarafından tanımlanan değere ulaşıncaya kadar dinamik olarak ayrılır StringBuilder.MaxCapacity .Additional memory for the StringBuilder object is allocated dynamically until it reaches the value defined by the StringBuilder.MaxCapacity property. Maksimum kapasiteye ulaşıldığında, nesne için daha fazla bellek ayrılamaz StringBuilder ve en yüksek kapasitenin ötesinde karakter eklemeye ya da bir ArgumentOutOfRangeException OutOfMemoryException özel durum oluşturur.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.

Aşağıdaki örnek, nesnesine StringBuilder Atanan dize genişliyorsa nesnenin yeni belleği nasıl ayırdığını ve kapasitesini dinamik olarak nasıl artırdığını gösterir.The following example illustrates how a StringBuilder object allocates new memory and increases its capacity dynamically as the string assigned to the object expands. Kod, StringBuilder varsayılan (parametresiz) oluşturucuyu çağırarak bir nesne oluşturur.The code creates a StringBuilder object by calling its default (parameterless) constructor. Bu nesnenin varsayılan kapasitesi 16 karakterdir ve maksimum kapasitesi 2.000.000.000 karakterden daha fazla.The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters. "This bir cümle" dizesini ekleme.Appending the string "This is a sentence." dize uzunluğu (19 karakter) nesnenin varsayılan kapasitesini aştığından yeni bir bellek ayırmaya neden olur StringBuilder .results in a new memory allocation because the string length (19 characters) exceeds the default capacity of the StringBuilder object. Nesnenin kapasitesi 32 karakter olarak ikiye katlanır, yeni dize eklenir ve nesnenin uzunluğu artık 19 karaktere eşittir.The capacity of the object doubles to 32 characters, the new string is added, and the length of the object now equals 19 characters. Daha sonra kod, "Bu ek bir cümle" dizesini ekler.The code then appends the string "This is an additional sentence." StringBuilder11 defa nesnenin değerine.to the value of the StringBuilder object 11 times. Append işlemi StringBuilder nesnenin uzunluğunun kapasitesini aşmasına neden olduğunda, mevcut kapasitesi iki katına çıkar ve Append işlem başarılı olur.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

Bellek ayırmaMemory allocation

Bir nesnenin varsayılan kapasitesi StringBuilder 16 karakterdir ve varsayılan en büyük kapasitesi ' dir Int32.MaxValue .The default capacity of a StringBuilder object is 16 characters, and its default maximum capacity is Int32.MaxValue. StringBuilder()Ve oluşturucularını çağırdığınızda bu varsayılan değerler kullanılır StringBuilder(String) .These default values are used if you call the StringBuilder() and StringBuilder(String) constructors.

Bir nesnenin ilk kapasitesini StringBuilder aşağıdaki yollarla açıkça tanımlayabilirsiniz:You can explicitly define the initial capacity of a StringBuilder object in the following ways:

  • StringBuilderNesnesini oluştururken bir parametre içeren oluşturuculardan herhangi birini çağırarak capacity .By calling any of the StringBuilder constructors that includes a capacity parameter when you create the object.

  • StringBuilder.CapacityVarolan bir nesneyi genişletmek için özelliği açıkça yeni bir değer atayarak StringBuilder .By explicitly assigning a new value to the StringBuilder.Capacity property to expand an existing StringBuilder object. Yeni kapasite var olan kapasiteden azsa veya StringBuilder nesnenin maksimum kapasitesinden daha fazlaysa, özelliğinin bir özel durum yaratdığına unutmayın.Note that the property throws an exception if the new capacity is less than the existing capacity or greater than the StringBuilder object's maximum capacity.

  • StringBuilder.EnsureCapacityYöntemini yeni kapasiteyle çağırarak.By calling the StringBuilder.EnsureCapacity method with the new capacity. Yeni kapasite, StringBuilder nesnenin maksimum kapasitesinden büyük olmamalıdır.The new capacity must not be greater than the StringBuilder object's maximum capacity. Ancak, özellik atamasının aksine Capacity , EnsureCapacity istenen yeni kapasite var olan kapasiteden küçükse bir özel durum oluşturmaz; bu durumda, yöntem çağrısının etkisi olmaz.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.

StringBuilderOluşturucu çağrısındaki nesneye atanan dize uzunluğu varsayılan kapasiteyi veya belirtilen kapasiteyi aşarsa, Capacity özelliği parametresiyle belirtilen dize uzunluğuna ayarlanır value ...If the length of the string assigned to the StringBuilder object in the constructor call exceeds either the default capacity or the specified capacity, the Capacity property is set to the length of the string specified with the value parameter.

Oluşturucuyu çağırarak bir nesnenin maksimum kapasitesini açık bir şekilde tanımlayabilirsiniz StringBuilder StringBuilder(Int32, Int32) .You can explicitly define the maximum capacity of a StringBuilder object by calling the StringBuilder(Int32, Int32) constructor. Salt okunurdur olduğundan, özelliğe yeni bir değer atayarak maksimum kapasiteyi değiştiremezsiniz MaxCapacity .You can't change the maximum capacity by assigning a new value to the MaxCapacity property, because it is read-only.

Önceki bölümde gösterildiği gibi, mevcut kapasite yetersiz olduğunda, ek bellek ayrılır ve bir nesnenin kapasitesi, StringBuilder özelliği tarafından tanımlanan değere kadar ikiye katlanır MaxCapacity .As the previous section shows, whenever the existing capacity is inadequate, additional memory is allocated and the capacity of a StringBuilder object doubles up to the value defined by the MaxCapacity property.

Genel olarak, varsayılan kapasite ve en yüksek kapasite çoğu uygulama için yeterlidir.In general, the default capacity and maximum capacity are adequate for most apps. Bu değerleri aşağıdaki koşullarda ayarlamayı düşünebilirsiniz:You might consider setting these values under the following conditions:

  • Nesnenin nihai boyutu StringBuilder büyük olasılıkla, genellikle birkaç megabayttan fazla bir şekilde büyüyerek artmaya devam ediyor.If the eventual size of the StringBuilder object is likely to grow exceedingly large, typically in excess of several megabytes. Bu durumda, Capacity çok fazla bellek yeniden konumu gereksinimini ortadan kaldırmak için ilk özelliği önemli ölçüde yüksek bir değere ayarlamanın bazı performans avantajları olabilir.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.

  • Uygulamanız sınırlı belleğe sahip bir sistemde çalışıyorsa.If your app is running on a system with limited memory. Bu durumda, MaxCapacity Int32.MaxValue uygulamanızın, bellek kısıtlı bir ortamda yürütülmesine neden olabilecek büyük dizeleri işliyorsa, özelliği değerinden küçük olarak ayarlamayı düşünmek isteyebilirsiniz.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.

Bir StringBuilder Nesnesini ÖrneklemeInstantiating a StringBuilder object

StringBuilderAşağıdaki tabloda listelenen altı yüklenmiş sınıf oluşturucularından birini çağırarak bir nesneyi örnekleyebilirsiniz.You instantiate a StringBuilder object by calling one of its six overloaded class constructors, which are listed in the following table. Kuruculardan üçü StringBuilder değeri boş bir dize olan, ancak Capacity değerlerini farklı şekilde ayarlanmış bir nesne örneğini oluşturur MaxCapacity .Three of the constructors instantiate a StringBuilder object whose value is an empty string, but set its Capacity and MaxCapacity values differently. Kalan üç Oluşturucu, belirli bir StringBuilder dize değerine ve kapasiteye sahip bir nesnesi tanımlar.The remaining three constructors define a StringBuilder object that has a specific string value and capacity. Üç oluşturucuların ikisi varsayılan maksimum kapasitesini kullanır Int32.MaxValue , ancak üçüncüsü maksimum kapasiteyi ayarlamanıza olanak sağlar.Two of the three constructors use the default maximum capacity of Int32.MaxValue, whereas the third allows you to set the maximum capacity.

OluşturucuConstructor Dize değeriString value KapasiteCapacity Maksimum kapasiteMaximum capacity
StringBuilder() String.Empty 1616 Int32.MaxValue
StringBuilder(Int32) String.Empty Parametre tarafından tanımlanan capacityDefined by the capacity parameter Int32.MaxValue
StringBuilder(Int32, Int32) String.Empty Parametre tarafından tanımlanan capacityDefined by the capacity parameter Parametre tarafından tanımlanan maxCapacityDefined by the maxCapacity parameter
StringBuilder(String) Parametre tarafından tanımlanan valueDefined by the value parameter 16 veya value .16 or value. Length, hangisi daha büyükseLength, whichever is greater Int32.MaxValue
StringBuilder(String, Int32) Parametre tarafından tanımlanan valueDefined by the value parameter capacityYa da parametresi tarafından tanımlanır value .Defined by the capacity parameter or value. Length, hangisi daha büyüktür.Length, whichever is greater. Int32.MaxValue
StringBuilder(String, Int32, Int32, Int32) Tarafından tanımlanır value .Defined by value. Substring(startIndex, length)Substring(startIndex, length) capacityYa da parametresi tarafından tanımlanır value .Defined by the capacity parameter or value. Length, hangisi daha büyüktür.Length, whichever is greater. Int32.MaxValue

Aşağıdaki örnek, nesneleri örneklemek için bu Oluşturucu aşırı yüklemelerinin üçünü kullanır StringBuilder .The following example uses three of these constructor overloads to instantiate StringBuilder objects.

using System;
using System.Text;

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

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

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

StringBuilder yöntemlerini çağırmaCalling StringBuilder methods

Bir örnekteki dizeyi değiştiren yöntemlerin çoğu, StringBuilder aynı örneğe bir başvuru döndürür.Most of the methods that modify the string in a StringBuilder instance return a reference to that same instance. Bu, StringBuilder yöntemleri iki şekilde çağırmanızı sağlar:This enables you to call StringBuilder methods in two ways:

  • Aşağıdaki örnekte olduğu gibi, tek tek yöntemi geri dönüş değerini çağırır ve yok sayabilirsiniz.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.
    
  • Tek bir ifadede bir dizi yöntem çağrısı yapabilirsiniz.You can make a series of method calls in a single statement. Art arda işlemler zincirler için tek bir ifade yazmak istiyorsanız bu kullanışlı olabilir.This can be convenient if you want to write a single statement that chains successive operations. Aşağıdaki örnek, önceki örnekteki üç yöntem çağrılarını tek bir kod satırına birleştirir.The following example consolidates three method calls from the previous example into a single line of code.

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

StringBuilder işlemleri gerçekleştirmePerforming StringBuilder operations

StringBuilderBir nesnedeki karakterleri yinelemek, eklemek, silmek veya değiştirmek için sınıfının yöntemlerini kullanabilirsiniz StringBuilder .You can use the methods of the StringBuilder class to iterate, add, delete, or modify characters in a StringBuilder object.

StringBuilder karakterlerini yinelemeIterating StringBuilder characters

StringBuilderÖzelliğini kullanarak bir nesnedeki karakterlere erişebilirsiniz StringBuilder.Chars[] .You can access the characters in a StringBuilder object by using the StringBuilder.Chars[] property. C# ' de Chars[] bir Dizin Oluşturucu; Visual Basic içinde, sınıfının varsayılan özelliğidir StringBuilder .In C#, Chars[] is an indexer; in Visual Basic, it is the default property of the StringBuilder class. Bu, özelliğe açıkça başvurulmadan tek tek karakterleri yalnızca dizinini kullanarak ayarlamanıza veya almanıza olanak sağlar Chars[] .This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the Chars[] property. StringBuilderNesnedeki karakterler 0 (sıfır) dizininde başlar ve Dizin-1 ' e geçin Length .Characters in a StringBuilder object begin at index 0 (zero) and continue to index Length - 1.

Aşağıdaki örnek, özelliğini gösterir Chars[] .The following example illustrates the Chars[] property. Bir nesneye on rastgele sayı ekler StringBuilder ve sonra her karakteri yineler.It appends ten random numbers to a StringBuilder object, and then iterates each character. Karakterin Unicode kategorisi varsa UnicodeCategory.DecimalDigitNumber , sayıyı 1 ' i düşürür (veya değeri 0 ise, sayıyı 9 olarak değiştirir).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). Örnek, StringBuilder tek tek karakterlerin değerleri değiştirildikten önce ve sonra nesnenin içeriğini görüntüler.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

Özelliği ile karakter tabanlı dizin oluşturma kullanmak Chars[] aşağıdaki koşullarda son derece yavaş olabilir:Using character-based indexing with the Chars[] property can be extremely slow under the following conditions:

Her karakter erişimi, dizine eklenecek doğru arabelleği bulmak için tüm bağlantılı Öbek listesini öğrentiğinden, performans ciddi bir şekilde etkilenir.Performance is severely impacted because each character access walks the entire linked list of chunks to find the correct buffer to index into.

Not

Büyük bir "parçalama" nesnesi için bile StringBuilder , Chars[] bir veya az sayıda karaktere yönelik dizin tabanlı erişim özelliğinin kullanılması, daha fazla performans etkisine sahiptir; genellikle 0 (n) bir işlemdir.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. StringBuilderBir O (n ^ 2) işlemi olan nesne içindeki karakterleri yineleirken önemli performans etkisi oluşur.The significant performance impact occurs when iterating the characters in the StringBuilder object, which is an O(n^2) operation.

Nesnelerle karakter tabanlı dizin oluşturma kullanırken performans sorunlarıyla karşılaşırsanız StringBuilder , aşağıdaki geçici çözümlerden birini kullanabilirsiniz:If you encounter performance issues when using character-based indexing with StringBuilder objects, you can use any of the following workarounds:

  • StringBuilderYöntemini çağırarak örneği öğesine dönüştürün String ToString ve sonra dizedeki karakterlere erişin.Convert the StringBuilder instance to a String by calling the ToString method, then access the characters in the string.

  • Varolan StringBuilder nesnenin içeriğini yeni bir önceden boyutlandırılabilir StringBuilder nesneye kopyalayın.Copy the contents of the existing StringBuilder object to a new pre-sized StringBuilder object. Yeni nesne parçalama yaptığından performans artar StringBuilder .Performance improves because the new StringBuilder object is not chunky. Örneğin: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)
    
  • Oluşturucuyu çağırarak, nesnenin başlangıç kapasitesini StringBuilder en büyük beklenen boyutuna yaklaşık olarak eşit bir değere ayarlayın StringBuilder(Int32) .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. Bunun, StringBuilder en yüksek kapasiteye nadiren ulaşırsa bile tüm bellek bloğunu ayırdığını unutmayın.Note that this allocates the entire block of memory even if the StringBuilder rarely reaches its maximum capacity.

Bir StringBuilder nesnesine metin eklemeAdding text to a StringBuilder object

StringBuilderSınıfı, bir nesnenin içeriğini genişletmek için aşağıdaki yöntemleri içerir StringBuilder :The StringBuilder class includes the following methods for expanding the contents of a StringBuilder object:

  • AppendYöntemi bir dize, bir alt dize, bir karakter dizisi, bir karakter dizisinin bir kısmı, birden çok kez yinelenen tek bir karakter veya bir nesneye basit veri türünün dize gösterimini ekler StringBuilder .The Append method appends a string, a substring, a character array, a portion of a character array, a single character repeated multiple times, or the string representation of a primitive data type to a StringBuilder object.

  • AppendLineYöntemi bir satır Sonlandırıcı veya bir dize bir nesne Sonlandırıcı ile birlikte bir dize ekler StringBuilder .The AppendLine method appends a line terminator or a string along with a line terminator to a StringBuilder object.

  • AppendFormatYöntemi bir nesneye bileşik biçim dizesi ekler StringBuilder .The AppendFormat method appends a composite format string to a StringBuilder object. Sonuç dizesinde yer alan nesnelerin dize temsilleri, geçerli sistem kültürünün veya belirtilen kültürün biçimlendirme kurallarını yansıtabilir.The string representations of objects included in the result string can reflect the formatting conventions of the current system culture or a specified culture.

  • Yöntemi, bir dize, bir alt dize Insert , bir dizenin birden çok yinelemesi, bir karakter dizisi, bir karakter dizisinin bir kısmı veya nesne içinde belirtilen konumda ilkel bir veri türünün dize temsili ekler StringBuilder .The Insert method inserts a string, a substring, multiple repetitions of a string, a character array, a portion of a character array, or the string representation of a primitive data type at a specified position in the StringBuilder object. Konum, sıfır tabanlı bir dizin tarafından tanımlanır.The position is defined by a zero-based index.

Aşağıdaki örnek Append , AppendLine AppendFormat Insert bir nesnesinin metnini genişletmek için,, ve yöntemlerini kullanır StringBuilder .The following example uses the Append, AppendLine, AppendFormat, and Insert methods to expand the text of a StringBuilder object.

using System;
using System.Text;

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

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

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

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

Bir StringBuilder nesnesinden metin silmeDeleting text from a StringBuilder object

StringBuilderSınıfı, geçerli örneğin boyutunu azaltan yöntemleri içerir StringBuilder .The StringBuilder class includes methods that can reduce the size of the current StringBuilder instance. ClearYöntemi tüm karakterleri kaldırır ve Length özelliği sıfır olarak ayarlar.The Clear method removes all characters and sets the Length property to zero. RemoveYöntemi belirli bir dizin konumundan başlayarak belirtilen sayıda karakteri siler.The Remove method deletes a specified number of characters starting at a particular index position. Buna ek olarak, StringBuilder Length özelliğini geçerli örneğin uzunluğundan daha küçük bir değere ayarlayarak bir nesnenin sonundaki karakterleri kaldırabilirsiniz.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.

Aşağıdaki örnek bir nesnesinden bazı metinleri kaldırır StringBuilder , sonuçta elde edilen kapasitesini, en yüksek kapasiteyi ve uzunluk özelliği değerlerini görüntüler ve ardından Clear nesnesinden tüm karakterleri kaldırmak için yöntemini çağırır StringBuilder .The following example removes some of the text from a StringBuilder object, displays its resulting capacity, maximum capacity, and length property values, and then calls the Clear method to remove all the characters from the StringBuilder object.

using System;
using System.Text;

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

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

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

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

Bir StringBuilder nesnesindeki metni değiştirmeModifying the text in a StringBuilder object

StringBuilder.ReplaceYöntemi, tüm StringBuilder nesnedeki veya belirli bir karakter aralığındaki bir karakterin veya dizenin tüm oluşumlarını değiştirir.The StringBuilder.Replace method replaces all occurrences of a character or a string in the entire StringBuilder object or in a particular character range. Aşağıdaki örnek, Replace nesnesinde soru işareti (?) ile tüm ünlem işaretlerini (!) değiştirmek için yöntemini kullanır StringBuilder .The following example uses the Replace method to replace all exclamation points (!) with question marks (?) in the StringBuilder object.

using System;
using System.Text;

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

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

Bir StringBuilder nesnesinde metin aramaSearching the text in a StringBuilder object

StringBuilderSınıfı String.Contains , String.IndexOf sınıfının, ve String.StartsWith String belirli bir karakter veya alt dize için arama yapmanıza olanak tanıyan,, ve yöntemlerine benzer yöntemler içermez.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. Bir alt dizenin varlığı veya başlangıç karakter konumunun belirlenmesi, bir String dize arama yöntemi ya da bir normal ifade yöntemi kullanarak bir değer aramanızı gerektirir.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. Aşağıdaki tabloda gösterildiği gibi, bu aramaları uygulamak için dört yol vardır.There are four ways to implement such searches, as the following table shows.

TeknikTechnique AvantajlarPros DezavantajlarCons
Nesneye eklemeden önce dize değerlerini arayın StringBuilder .Search string values before adding them to the StringBuilder object. Alt dizenin mevcut olup olmadığını belirlemek için faydalıdır.Useful for determining whether a substring exists. Bir alt dizenin dizin konumu önemli olduğunda kullanılamaz.Cannot be used when the index position of a substring is important.
ToStringDöndürülen nesneyi çağırın ve arayın String .Call ToString and search the returned String object. Tüm metni bir StringBuilder nesneye atarsanız ve sonra değiştirmeye başladığınızda kullanımı kolay.Easy to use if you assign all the text to a StringBuilder object, and then begin to modify it. ToStringTüm metinler nesneye eklenmeden önce değişiklikler yapmanız gerekiyorsa, tekrar tekrar tekrar arama yapın StringBuilder .Cumbersome to repeatedly call ToString if you must make modifications before all text is added to the StringBuilder object.

Değişiklik yapıyorsanız nesnenin metninin sonundan çalışmayı unutmamanız gerekir StringBuilder .You must remember to work from the end of the StringBuilder object's text if you're making changes.
Chars[]Bir karakter aralığını sıralı olarak aramak için özelliğini kullanın.Use the Chars[] property to sequentially search a range of characters. Bağımsız karakterlerle veya küçük bir alt dizeyle ilgileniyorsanız faydalıdır.Useful if you're concerned with individual characters or a small substring. Arama için karakter sayısı büyükse veya arama mantığı karmaşık ise, kısabersome.Cumbersome if the number of characters to search is large or if the search logic is complex.

Yinelenen Yöntem çağrıları aracılığıyla çok büyük büyümüş nesneler için çok kötü performansa neden olur.Results in very poor performance for objects that have grown very large through repeated method calls.
Nesneyi nesnesine dönüştürüp nesne StringBuilder String üzerinde değişiklikler yapın String .Convert the StringBuilder object to a String object, and perform modifications on the String object. Değişiklik sayısı küçükse yararlı olur.Useful if the number of modifications is small. Değişiklik sayısı büyükse, sınıfın performans avantajını geçersiz kılar StringBuilder .Negates the performance benefit of the StringBuilder class if the number of modifications is large.

Daha ayrıntılı bilgi için bu teknikleri inceleyelim.Let's examine these techniques in greater detail.

  • Aramanın hedefi belirli bir alt dizenin mevcut olup olmadığını (yani, alt dizenin konumu ile ilgilenmiyorsanız) tespit etmek ise, dizeleri nesnede depolamadan önce arama yapabilirsiniz StringBuilder .If the goal of the search is to determine whether a particular substring exists (that is, if you aren't interested in the position of the substring), you can search strings before storing them in the StringBuilder object. Aşağıdaki örnek, olası bir uygulama sağlar.The following example provides one possible implementation. StringBuilderFinderOluşturucuya bir nesneye başvuru geçilen StringBuilder ve dizede bulunacak alt dizenin bulunduğu bir sınıfı tanımlar.It defines a StringBuilderFinder class whose constructor is passed a reference to a StringBuilder object and the substring to find in the string. Bu durumda, örnek, kayıtlı sıcaklıkların Fahrenhaymı mi yoksa santimi olduğunu belirlemeyi dener ve uygun giriş metnini nesnenin başlangıcına ekler StringBuilder .In this case, the example tries to determine whether recorded temperatures are in Fahrenheit or Celsius, and adds the appropriate introductory text to the beginning of the StringBuilder object. Rastgele bir sayı Oluşturucu, veri içeren bir diziyi veya derece Fahrenhayt cinsinden verileri içeren bir dizi seçmek için kullanılır.A random number generator is used to select an array that contains data in either degrees Celsius or degrees Fahrenheit.

    using System;
    using System.Text;
    
    public class Example
    {
       public static void Main()
       {
          Random rnd = new Random();
          string[] tempF = { "47.6F", "51.3F", "49.5F", "62.3F" };
          string[] tempC = { "21.2C", "16.1C", "23.5C", "22.9C" };
          string[][] temps = { tempF, tempC }; 
    
          StringBuilder sb = new StringBuilder();
          var f = new StringBuilderFinder(sb, "F");
          var baseDate = new DateTime(2013, 5, 1); 
          String[] temperatures = temps[rnd.Next(2)];
          bool isFahrenheit = false;
          foreach (var temperature in temperatures) {
             if (isFahrenheit)
                sb.AppendFormat("{0:d}: {1}\n", baseDate, temperature);
             else
                isFahrenheit = f.SearchAndAppend(String.Format("{0:d}: {1}\n", 
                                                 baseDate, temperature));
             baseDate = baseDate.AddDays(1);
          }            
          if (isFahrenheit) {
             sb.Insert(0, "Average Daily Temperature in Degrees Fahrenheit");
             sb.Insert(47, "\n\n");
          }
          else {
             sb.Insert(0, "Average Daily Temperature in Degrees Celsius");
             sb.Insert(44, "\n\n");
          }   
          Console.WriteLine(sb.ToString());
       }
    }
    
    public class StringBuilderFinder
    {
       private StringBuilder sb;
       private String text;
       
       public StringBuilderFinder(StringBuilder sb, String textToFind)
       {
          this.sb = sb;
          this.text = textToFind;
       }
       
       public bool SearchAndAppend(String stringToSearch)
       {
          sb.Append(stringToSearch);
          return stringToSearch.Contains(text);
       }
    }
    // The example displays output similar to the following:
    //    Average Daily Temperature in Degrees Celsius
    //    
    //    5/1/2013: 21.2C
    //    5/2/2013: 16.1C
    //    5/3/2013: 23.5C
    //    5/4/2013: 22.9C
    
    Imports System.Text
    
    Module Example
       Public Sub Main()
          Dim rnd As New Random()
          Dim tempF() As String = { "47.6F", "51.3F", "49.5F", "62.3F" }
          Dim tempC() As String = { "21.2C", "16.1C", "23.5C", "22.9C" }
          Dim temps()() As String = { tempF, tempC } 
    
          Dim sb As StringBuilder = New StringBuilder()
          Dim f As New StringBuilderFinder(sb, "F")
          Dim baseDate As New DateTime(2013, 5, 1) 
          Dim temperatures() As String = temps(rnd.Next(2))
          Dim isFahrenheit As Boolean = False
          For Each temperature In temperatures
             If isFahrenheit Then
                sb.AppendFormat("{0:d}: {1}{2}", baseDate, temperature, vbCrLf)
             Else
                isFahrenheit = f.SearchAndAppend(String.Format("{0:d}: {1}{2}", 
                                                 baseDate, temperature, vbCrLf))
             End If
             baseDate = baseDate.AddDays(1)
          Next            
          If isFahrenheit Then
             sb.Insert(0, "Average Daily Temperature in Degrees Fahrenheit")
             sb.Insert(47, vbCrLf + vbCrLf)
          Else
             sb.Insert(0, "Average Daily Temperature in Degrees Celsius")
             sb.Insert(44, vbCrLf + vbCrLf)
          End If   
          Console.WriteLine(sb.ToString())
       End Sub
    End Module
    
    Public Class StringBuilderFinder
       Private sb As StringBuilder
       Private text As String
       
       Public Sub New(sb As StringBuilder, textToFind As String)
          Me.sb = sb
          text = textToFind
       End Sub
       
       Public Function SearchAndAppend(stringToSearch As String) As Boolean
          sb.Append(stringToSearch)
          Return stringToSearch.Contains(text)
       End Function
    End Class
    ' The example displays output similar to the following:
    '    Average Daily Temperature in Degrees Celsius
    '    
    '    5/1/2013: 21.2C
    '    5/2/2013: 16.1C
    '    5/3/2013: 23.5C
    '    5/4/2013: 22.9C
    
  • StringBuilder.ToStringNesneyi nesnesine dönüştürmek için yöntemini çağırın StringBuilder String .Call the StringBuilder.ToString method to convert the StringBuilder object to a String object. Veya gibi yöntemleri kullanarak dizeyi arayabilir String.LastIndexOf String.StartsWith veya Regex desen aramak için normal ifadeleri ve sınıfı kullanabilirsiniz.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. Hem hem StringBuilder de String nesneleri karakterleri depolamak için UTF-16 kodlaması kullandığından karakterlerin, alt dizelerin ve normal ifade eşleştirmelerinin dizin konumları her iki nesnede de aynıdır.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. Bu, üzerinde metnin bulunduğu StringBuilder konumda değişiklik yapmak için yöntemleri kullanmanıza olanak sağlar String .This enables you to use StringBuilder methods to make changes at the same position at which that text is found in the String object.

    Not

    Bu yaklaşımı benimsediğinizde, nesneyi StringBuilder tekrar tekrar bir dizeye dönüştürmeniz gerekmiyorsa nesnenin sonundan itibaren çalışmanız gerekir StringBuilder .If you adopt this approach, you should work from the end of the StringBuilder object to its beginning so that you don't have to repeatedly convert the StringBuilder object to a string.

    Aşağıdaki örnek bu yaklaşımı gösterir.The following example illustrates this approach. Bir nesnedeki her bir Ingilizce alfabede bulunan dört adet tekrarı depolar StringBuilder .It stores four occurrences of each letter of the English alphabet in a StringBuilder object. Daha sonra metni bir String nesnesine dönüştürür ve dört karakterlik sıranın başlangıç konumunu belirlemek için normal bir ifade kullanır.It then converts the text to a String object and uses a regular expression to identify the starting position of each four-character sequence. Son olarak, ilk dizi hariç dört karakterlik her bir çizgiden önce bir alt çizgi ekler ve dizinin ilk karakterini büyük harfe dönüştürür.Finally, it adds an underscore before each four-character sequence except for the first sequence, and converts the first character of the sequence to uppercase.

    using System;
    using System.Text;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          // Create a StringBuilder object with 4 successive occurrences 
          // of each character in the English alphabet. 
          StringBuilder sb = new StringBuilder();
          for (ushort ctr = (ushort)'a'; ctr <= (ushort) 'z'; ctr++)
             sb.Append(Convert.ToChar(ctr), 4);
          
          // Create a parallel string object.
          String sbString = sb.ToString();
          // Determine where each new character sequence begins.
          String pattern = @"(\w)\1+";
          MatchCollection matches = Regex.Matches(sbString, pattern);
    
          // Uppercase the first occurrence of the sequence, and separate it
          // from the previous sequence by an underscore character.
          for (int ctr = matches.Count - 1; ctr >= 0; ctr--) { 
             Match m = matches[ctr];
             sb[m.Index] = Char.ToUpper(sb[m.Index]);
             if (m.Index > 0) sb.Insert(m.Index, "_");
          }
          // Display the resulting string.
          sbString = sb.ToString();
          int line = 0;
          do {
             int nChars = line * 80 + 79 <= sbString.Length ? 
                                 80 : sbString.Length - line * 80;
             Console.WriteLine(sbString.Substring(line * 80, nChars));
             line++;
          } while (line * 80 < sbString.Length);
       }
    }
    // The example displays the following output:
    //    Aaaa_Bbbb_Cccc_Dddd_Eeee_Ffff_Gggg_Hhhh_Iiii_Jjjj_Kkkk_Llll_Mmmm_Nnnn_Oooo_Pppp_
    //    Qqqq_Rrrr_Ssss_Tttt_Uuuu_Vvvv_Wwww_Xxxx_Yyyy_Zzzz
    
    Imports System.Text
    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          ' Create a StringBuilder object with 4 successive occurrences 
          ' of each character in the English alphabet. 
          Dim sb As New StringBuilder()
          For ctr As UShort = AscW("a") To Ascw("z")
             sb.Append(ChrW(ctr), 4)
          Next    
          ' Create a parallel string object.
          Dim sbString As String = sb.ToString()
          ' Determine where each new character sequence begins.
          Dim pattern As String = "(\w)\1+"
          Dim matches As MatchCollection = Regex.Matches(sbString, pattern)
    
          ' Uppercase the first occurrence of the sequence, and separate it
          ' from the previous sequence by an underscore character.
          For ctr As Integer = matches.Count - 1 To 0 Step -1 
             Dim m As Match = matches(ctr)
             sb.Chars(m.Index) = Char.ToUpper(sb.Chars(m.index))
             If m.Index > 0 Then sb.Insert(m.Index, "_")
          Next
          ' Display the resulting string.
          sbString = sb.ToString()
          Dim line As Integer = 0
          Do
             Dim nChars As Integer = If(line * 80 + 79 <= sbString.Length, 
                                        80, sbString.Length - line * 80)
             Console.WriteLine(sbString.Substring(line * 80, nChars))
             line += 1
          Loop While line * 80 < sbString.Length
       End Sub
    End Module
    ' The example displays the following output:
    '    Aaaa_Bbbb_Cccc_Dddd_Eeee_Ffff_Gggg_Hhhh_Iiii_Jjjj_Kkkk_Llll_Mmmm_Nnnn_Oooo_Pppp_
    '    Qqqq_Rrrr_Ssss_Tttt_Uuuu_Vvvv_Wwww_Xxxx_Yyyy_Zzzz
    
  • StringBuilder.Chars[]Bir nesne içindeki bir karakter aralığını sıralı olarak aramak için özelliğini kullanın StringBuilder .Use the StringBuilder.Chars[] property to sequentially search a range of characters in a StringBuilder object. Aranacak karakter sayısı büyükse veya arama mantığı özellikle karmaşıksa bu yaklaşım pratik olmayabilir.This approach may not be practical if the number of characters to be searched is large or the search logic is particularly complex. Çok büyük, öbekli nesneler için karakter karakter temelli dizin tabanlı erişimin performans etkileri için StringBuilder , özelliği için belgelere bakın StringBuilder.Chars[] .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.

    Aşağıdaki örnek, önceki örnekteki işlevlerle aynıdır, ancak uygulamada farklılık gösterir.The following example is identical in functionality to the previous example but differs in implementation. Chars[]Bir karakter değerinin değiştiğini algılamak için özelliğini kullanır, bu konuma bir alt çizgi ekler ve yeni dizideki ilk karakteri büyük harfe dönüştürür.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
    
  • Nesnedeki tüm değiştirilmemiş metni depolayın, nesneyi nesnesine StringBuilder StringBuilder.ToString dönüştürmek için yöntemini çağırın StringBuilder String ve nesne üzerindeki değişiklikleri gerçekleştirin String .Store all the unmodified text in the StringBuilder object, call the StringBuilder.ToString method to convert the StringBuilder object to a String object, and perform the modifications on the String object. Yalnızca birkaç değişiklik varsa, bu yaklaşımı kullanabilirsiniz; Aksi takdirde, sabit dizeler ile çalışmanın maliyeti bir nesne kullanmanın performans avantajlarını bozabilir 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.

    Aşağıdaki örnek, önceki iki örneğe yönelik işlevselliklerle aynıdır, ancak uygulamada farklılık gösterir.The following example is identical in functionality to the previous two examples but differs in implementation. Bir nesnesi oluşturur StringBuilder , bir nesnesine dönüştürür String ve sonra dize üzerinde kalan tüm değişiklikleri gerçekleştirmek için normal bir ifade kullanır.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)Yöntemi her bir eşleşimde değişikliği gerçekleştirmek için bir lambda ifadesi kullanır.The Regex.Replace(String, String, MatchEvaluator) method uses a lambda expression to perform the replacement on each match.

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

StringBuilder nesnesini dizeye dönüştürmeConverting the StringBuilder object to a string

StringBuilder String Nesnesi tarafından temsil edilen dizeyi parametresi olan bir yönteme geçirebilmeniz StringBuilder String veya Kullanıcı arabiriminde gösterebilmeniz için nesneyi bir nesnesine dönüştürmeniz gerekir.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. Bu dönüştürmeyi yöntemini çağırarak gerçekleştirirsiniz StringBuilder.ToString .You perform this conversion by calling the StringBuilder.ToString method. Bir çizim için, bir ToString StringBuilder nesneyi bir normal ifade yöntemine geçirilebilmesi için bir dizeye dönüştürmek üzere yöntemini çağıran önceki örneğe bakın.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.

Arayanlara Notlar

.NET Core ve .NET Framework 4,0 ve sonraki sürümlerinde, StringBuilder oluşturucuyu çağırarak nesneyi örneklediğinizde, StringBuilder(Int32, Int32) her ikisi de örneğin uzunluğu ve StringBuilder değeri, özelliğin değerinin ötesine büyüyebilir MaxCapacity .In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. Bu durum özellikle, Append(String) AppendFormat(String, Object) küçük dizeleri eklemek için ve yöntemlerini çağırdığınızda ortaya çıkabilir.This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.

Oluşturucular

StringBuilder()

StringBuilder sınıfının yeni bir örneğini başlatır.Initializes a new instance of the StringBuilder class.

StringBuilder(Int32)

StringBuilderBelirtilen kapasiteyi kullanarak sınıfının yeni bir örneğini başlatır.Initializes a new instance of the StringBuilder class using the specified capacity.

StringBuilder(Int32, Int32)

Belirtilen kapasiteye sahip bir sınıfın yeni bir örneğini başlatır StringBuilder ve belirtilen en büyük bir değer ile büyüyebilir.Initializes a new instance of the StringBuilder class that starts with a specified capacity and can grow to a specified maximum.

StringBuilder(String)

StringBuilderBelirtilen dizeyi kullanarak sınıfının yeni bir örneğini başlatır.Initializes a new instance of the StringBuilder class using the specified string.

StringBuilder(String, Int32)

StringBuilderBelirtilen dizeyi ve kapasiteyi kullanarak sınıfının yeni bir örneğini başlatır.Initializes a new instance of the StringBuilder class using the specified string and capacity.

StringBuilder(String, Int32, Int32, Int32)

StringBuilderBelirtilen alt dizeden ve kapasiteden sınıfın yeni bir örneğini başlatır.Initializes a new instance of the StringBuilder class from the specified substring and capacity.

Özellikler

Capacity

Geçerli örnek tarafından ayrılan belleğe dahil olabilecek en fazla karakter sayısını alır veya ayarlar.Gets or sets the maximum number of characters that can be contained in the memory allocated by the current instance.

Chars[Int32]

Bu örnekteki belirtilen karakter konumundaki karakteri alır veya ayarlar.Gets or sets the character at the specified character position in this instance.

Length

Geçerli nesnenin uzunluğunu alır veya ayarlar StringBuilder .Gets or sets the length of the current StringBuilder object.

MaxCapacity

Bu örneğin maksimum kapasitesini alır.Gets the maximum capacity of this instance.

Yöntemler

Append(Boolean)

Belirtilen Boolean değerin dize gösterimini bu örneğe ekler.Appends the string representation of a specified Boolean value to this instance.

Append(Byte)

Belirtilen 8 bit işaretsiz tamsayının dize temsilini bu örneğe ekler.Appends the string representation of a specified 8-bit unsigned integer to this instance.

Append(Char)

Belirtilen nesnenin dize temsilini Char Bu örneğe ekler.Appends the string representation of a specified Char object to this instance.

Append(Char*, Int32)

Belirtilen adresten bu örneğe başlayarak bir Unicode karakter dizisi ekler.Appends an array of Unicode characters starting at a specified address to this instance.

Append(Char, Int32)

Bu örneğe bir Unicode karakterinin dize gösteriminin belirtilen sayıda kopyasını ekler.Appends a specified number of copies of the string representation of a Unicode character to this instance.

Append(Char[])

Belirtilen bir dizideki Unicode karakterlerinin dize temsilini bu örneğe ekler.Appends the string representation of the Unicode characters in a specified array to this instance.

Append(Char[], Int32, Int32)

Bu örneğe, belirtilen bir Unicode karakter dizisinin dize gösterimini ekler.Appends the string representation of a specified subarray of Unicode characters to this instance.

Append(Decimal)

Belirtilen ondalık sayının dize temsilini bu örneğe ekler.Appends the string representation of a specified decimal number to this instance.

Append(Double)

Belirtilen çift duyarlıklı kayan noktalı sayının dize temsilini bu örneğe ekler.Appends the string representation of a specified double-precision floating-point number to this instance.

Append(Int16)

Belirtilen 16 bit işaretli tamsayının dize temsilini bu örneğe ekler.Appends the string representation of a specified 16-bit signed integer to this instance.

Append(Int32)

Belirtilen 32 bitlik işaretli tamsayının dize temsilini bu örneğe ekler.Appends the string representation of a specified 32-bit signed integer to this instance.

Append(Int64)

Belirtilen 64 bitlik işaretli tamsayının dize temsilini bu örneğe ekler.Appends the string representation of a specified 64-bit signed integer to this instance.

Append(Object)

Belirtilen nesnenin dize temsilini bu örneğe ekler.Appends the string representation of a specified object to this instance.

Append(ReadOnlyMemory<Char>)

Belirtilen salt okunurdur karakter bellek bölgesinin dize temsilini bu örneğe ekler.Appends the string representation of a specified read-only character memory region to this instance.

Append(ReadOnlySpan<Char>)

Belirtilen salt okunurdur bir karakter aralığının dize gösterimini bu örneğe ekler.Appends the string representation of a specified read-only character span to this instance.

Append(SByte)

Belirtilen 8 bit işaretli tamsayının dize temsilini bu örneğe ekler.Appends the string representation of a specified 8-bit signed integer to this instance.

Append(Single)

Belirtilen tek duyarlıklı kayan noktalı sayının dize temsilini bu örneğe ekler.Appends the string representation of a specified single-precision floating-point number to this instance.

Append(String)

Belirtilen dizenin bir kopyasını bu örneğe ekler.Appends a copy of the specified string to this instance.

Append(String, Int32, Int32)

Belirtilen alt dizenin bir kopyasını bu örneğe ekler.Appends a copy of a specified substring to this instance.

Append(StringBuilder)

Belirtilen dize oluşturucusunun dize temsilini bu örneğe ekler.Appends the string representation of a specified string builder to this instance.

Append(StringBuilder, Int32, Int32)

Belirtilen dize Oluşturucu içindeki alt dizenin bir kopyasını bu örneğe ekler.Appends a copy of a substring within a specified string builder to this instance.

Append(UInt16)

Belirtilen 16 bit işaretsiz tamsayının dize temsilini bu örneğe ekler.Appends the string representation of a specified 16-bit unsigned integer to this instance.

Append(UInt32)

Belirtilen 32 bitlik işaretsiz tamsayının dize temsilini bu örneğe ekler.Appends the string representation of a specified 32-bit unsigned integer to this instance.

Append(UInt64)

Belirtilen 64 bitlik işaretsiz tamsayının dize temsilini bu örneğe ekler.Appends the string representation of a specified 64-bit unsigned integer to this instance.

AppendFormat(IFormatProvider, String, Object)

Bu örneğe sıfır veya daha fazla biçim öğesi içeren bir bileşik biçim dizesi işleyerek döndürülen dizeyi ekler.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Her biçim öğesi, belirtilen biçim sağlayıcısını kullanan tek bir bağımsız değişkenin dize temsili ile değiştirilmiştir.Each format item is replaced by the string representation of a single argument using a specified format provider.

AppendFormat(IFormatProvider, String, Object, Object)

Bu örneğe sıfır veya daha fazla biçim öğesi içeren bir bileşik biçim dizesi işleyerek döndürülen dizeyi ekler.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Her biçim öğesi, belirtilen biçim sağlayıcısı kullanılarak iki bağımsız değişkenin her birinin dize temsili ile değiştirilmiştir.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)

Bu örneğe sıfır veya daha fazla biçim öğesi içeren bir bileşik biçim dizesi işleyerek döndürülen dizeyi ekler.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Her biçim öğesi, belirtilen biçim sağlayıcısı kullanılarak üç bağımsız değişkenin her birinin dize temsili ile değiştirilmiştir.Each format item is replaced by the string representation of either of three arguments using a specified format provider.

AppendFormat(IFormatProvider, String, Object[])

Bu örneğe sıfır veya daha fazla biçim öğesi içeren bir bileşik biçim dizesi işleyerek döndürülen dizeyi ekler.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Her biçim öğesi, belirtilen biçim sağlayıcısını kullanan bir parametre dizisindeki karşılık gelen bağımsız değişkenin dize temsili ile değiştirilmiştir.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)

Bu örneğe sıfır veya daha fazla biçim öğesi içeren bir bileşik biçim dizesi işleyerek döndürülen dizeyi ekler.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Her biçim öğesi, tek bir bağımsız değişkenin dize temsili ile değiştirilmiştir.Each format item is replaced by the string representation of a single argument.

AppendFormat(String, Object, Object)

Bu örneğe sıfır veya daha fazla biçim öğesi içeren bir bileşik biçim dizesi işleyerek döndürülen dizeyi ekler.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Her biçim öğesi iki bağımsız değişkenin dize temsili ile değiştirilmiştir.Each format item is replaced by the string representation of either of two arguments.

AppendFormat(String, Object, Object, Object)

Bu örneğe sıfır veya daha fazla biçim öğesi içeren bir bileşik biçim dizesi işleyerek döndürülen dizeyi ekler.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Her biçim öğesi üç bağımsız değişkenin dize temsili ile değiştirilmiştir.Each format item is replaced by the string representation of either of three arguments.

AppendFormat(String, Object[])

Bu örneğe sıfır veya daha fazla biçim öğesi içeren bir bileşik biçim dizesi işleyerek döndürülen dizeyi ekler.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Her biçim öğesi, bir parametre dizisindeki karşılık gelen bağımsız değişkenin dize temsili ile değiştirilmiştir.Each format item is replaced by the string representation of a corresponding argument in a parameter array.

AppendJoin(Char, Object[])

Her üye arasında belirtilen karakter ayırıcısını kullanarak, belirtilen nesne dizisinde öğelerin dize gösterimlerini birleştirir, sonra sonucu dize oluşturucusunun geçerli örneğine ekler.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[])

Her bir dize arasında belirtilen karakter ayırıcısını kullanarak, belirtilen dizinin dizelerini birleştirir, sonra sonucu dize oluşturucusunun geçerli örneğine ekler.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[])

Her üye arasındaki belirtilen ayırıcıyı kullanarak, belirtilen nesne dizisinde öğelerin dize gösterimlerini birleştirir, sonra sonucu dize oluşturucusunun geçerli örneğine ekler.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[])

Her bir dize arasında belirtilen ayırıcıyı kullanarak, belirtilen dizinin dizelerini birleştirir, sonra sonucu dize oluşturucusunun geçerli örneğine ekler.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>)

Her üye arasında belirtilen karakter ayırıcısını kullanarak bir koleksiyonun üyelerini birleştirir ve ekler.Concatenates and appends the members of a collection, using the specified char separator between each member.

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

Her üye arasında belirtilen ayırıcıyı kullanarak bir koleksiyonun üyelerini birleştirir ve ekler.Concatenates and appends the members of a collection, using the specified separator between each member.

AppendLine()

Varsayılan satır sonlandırıcıyı geçerli nesnenin sonuna ekler StringBuilder .Appends the default line terminator to the end of the current StringBuilder object.

AppendLine(String)

Belirtilen dizenin bir kopyasını, ardından varsayılan satır Sonlandırıcı tarafından geçerli nesnenin sonuna ekler StringBuilder .Appends a copy of the specified string followed by the default line terminator to the end of the current StringBuilder object.

Clear()

Geçerli örnekten tüm karakterleri kaldırır StringBuilder .Removes all characters from the current StringBuilder instance.

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

Bu örneğin belirtilen segmentinden gelen karakterleri, hedef dizinin belirtilen segmentine kopyalar Char .Copies the characters from a specified segment of this instance to a specified segment of a destination Char array.

CopyTo(Int32, Span<Char>, Int32)

Bu örneğin belirtilen segmentinden gelen karakterleri hedef Char aralığına kopyalar.Copies the characters from a specified segment of this instance to a destination Char span.

EnsureCapacity(Int32)

Bu örneğinin kapasitesinin StringBuilder en az belirtilen değere sahip olmasını sağlar.Ensures that the capacity of this instance of StringBuilder is at least the specified value.

Equals(Object)

Belirtilen nesnenin geçerli nesneye eşit olup olmadığını belirler.Determines whether the specified object is equal to the current object.

(Devralındığı yer: Object)
Equals(ReadOnlySpan<Char>)

Bu örnekteki karakterlerin belirtilen salt bir salt okunurdur karakter alanındaki karakterlere eşit olup olmadığını gösteren bir değer döndürür.Returns a value indicating whether the characters in this instance are equal to the characters in a specified read-only character span.

Equals(StringBuilder)

Bu örneğin, belirtilen bir nesneye eşit olup olmadığını gösteren bir değeri döndürür.Returns a value indicating whether this instance is equal to a specified object.

GetChunks()

Bu örnekten oluşturulmuş bir içinde temsil edilen karakterlerin öbeklerini yinelemek için kullanılabilecek bir nesne döndürür ReadOnlyMemory<Char> StringBuilder .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()

Varsayılan karma işlevi olarak işlev görür.Serves as the default hash function.

(Devralındığı yer: Object)
GetType()

TypeGeçerli örneği alır.Gets the Type of the current instance.

(Devralındığı yer: Object)
Insert(Int32, Boolean)

Belirtilen karakter konumunda bu örneğe bir Boole değeri dize gösterimini ekler.Inserts the string representation of a Boolean value into this instance at the specified character position.

Insert(Int32, Byte)

Belirtilen karakter konumunda bu örneğe belirtilen 8 bitlik işaretsiz bir tamsayı dize gösterimini ekler.Inserts the string representation of a specified 8-bit unsigned integer into this instance at the specified character position.

Insert(Int32, Char)

Belirtilen karakter konumunda belirtilen Unicode karakterinin dize gösterimini bu örneğe ekler.Inserts the string representation of a specified Unicode character into this instance at the specified character position.

Insert(Int32, Char[])

Belirtilen karakter konumunda bu örneğe belirtilen Unicode karakter dizisinin dize gösterimini ekler.Inserts the string representation of a specified array of Unicode characters into this instance at the specified character position.

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

Belirtilen karakter konumunda bu örneğe, belirtilen bir UNICODE karakter dizisi gösterimini ekler.Inserts the string representation of a specified subarray of Unicode characters into this instance at the specified character position.

Insert(Int32, Decimal)

Belirtilen karakter konumunda bu örneğe bir ondalık sayının dize gösterimini ekler.Inserts the string representation of a decimal number into this instance at the specified character position.

Insert(Int32, Double)

Bu örneğe, bir çift duyarlıklı kayan noktalı sayının dize gösterimini belirtilen karakter konumunda ekler.Inserts the string representation of a double-precision floating-point number into this instance at the specified character position.

Insert(Int32, Int16)

Belirtilen bir 16 bit işaretli tamsayının dize gösterimini, bu örneğe belirtilen karakter konumunda ekler.Inserts the string representation of a specified 16-bit signed integer into this instance at the specified character position.

Insert(Int32, Int32)

Belirtilen karakter konumunda, belirtilen 32 bitlik işaretli tamsayının dize gösterimini bu örneğe ekler.Inserts the string representation of a specified 32-bit signed integer into this instance at the specified character position.

Insert(Int32, Int64)

Bu örneğe, belirtilen karakter konumunda 64 bitlik bir işaretli tamsayının dize gösterimini ekler.Inserts the string representation of a 64-bit signed integer into this instance at the specified character position.

Insert(Int32, Object)

Belirtilen karakter konumunda bu örneğe bir nesnenin dize gösterimini ekler.Inserts the string representation of an object into this instance at the specified character position.

Insert(Int32, ReadOnlySpan<Char>)

Belirtilen karakter konumundaki bu örneğe karakter dizisini ekler.Inserts the sequence of characters into this instance at the specified character position.

Insert(Int32, SByte)

Belirtilen karakter konumunda bu örneğe belirtilen 8 bit işaretli tamsayının dize gösterimini ekler.Inserts the string representation of a specified 8-bit signed integer into this instance at the specified character position.

Insert(Int32, Single)

Belirtilen karakter konumundaki bu örneğe tek duyarlıklı kayan noktalı sayının dize gösterimini ekler.Inserts the string representation of a single-precision floating point number into this instance at the specified character position.

Insert(Int32, String)

Belirtilen karakter konumunda bu örneğe bir dize ekler.Inserts a string into this instance at the specified character position.

Insert(Int32, String, Int32)

Belirtilen karakter konumunda belirtilen bir dizenin bir veya daha fazla kopyasını bu örneğe ekler.Inserts one or more copies of a specified string into this instance at the specified character position.

Insert(Int32, UInt16)

Belirtilen karakter konumunda bu örneğe 16 bit işaretsiz tamsayının dize gösterimini ekler.Inserts the string representation of a 16-bit unsigned integer into this instance at the specified character position.

Insert(Int32, UInt32)

Bu örneğe, belirtilen karakter konumunda 32 bitlik işaretsiz bir tamsayı dize gösterimini ekler.Inserts the string representation of a 32-bit unsigned integer into this instance at the specified character position.

Insert(Int32, UInt64)

Bu örneğe, belirtilen karakter konumunda 64 bitlik işaretsiz bir tamsayı dize gösterimini ekler.Inserts the string representation of a 64-bit unsigned integer into this instance at the specified character position.

MemberwiseClone()

Geçerli bir basit kopyasını oluşturur Object .Creates a shallow copy of the current Object.

(Devralındığı yer: Object)
Remove(Int32, Int32)

Bu örnekten belirtilen karakter aralığını kaldırır.Removes the specified range of characters from this instance.

Replace(Char, Char)

Bu örnekteki belirtilen bir karakterin tüm oluşumlarını, belirtilen başka bir karakterle değiştirir.Replaces all occurrences of a specified character in this instance with another specified character.

Replace(Char, Char, Int32, Int32)

Bu örneğin bir alt dizesi içinde, belirtilen bir karakterin tüm oluşumlarını belirtilen karakterle değiştirir.Replaces, within a substring of this instance, all occurrences of a specified character with another specified character.

Replace(String, String)

Bu örnekteki belirtilen bir dizenin tüm oluşumlarını, belirtilen başka bir dizeyle değiştirir.Replaces all occurrences of a specified string in this instance with another specified string.

Replace(String, String, Int32, Int32)

Bu örneğin bir alt dizesinde, belirtilen bir dizenin bir belirtilen dize ile tüm tekrarlarını değiştirir.Replaces, within a substring of this instance, all occurrences of a specified string with another specified string.

ToString()

Bu örneğin değerini bir olarak dönüştürür String .Converts the value of this instance to a String.

ToString(Int32, Int32)

Bu örneğin bir alt dizenin değerini bir değerine dönüştürür String .Converts the value of a substring of this instance to a String.

Belirtik Arabirim Kullanımları

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

SerializationInfoNesneyi, geçerli nesnenin serisini kaldırmak için gereken verilerle doldurur StringBuilder .Populates a SerializationInfo object with the data necessary to deserialize the current StringBuilder object.

Şunlara uygulanır

Ayrıca bkz.