System.Text.StringBuilder sınıfı

Bu makale, bu API'nin başvuru belgelerine ek açıklamalar sağlar.

sınıfı, StringBuilder değeri değiştirilebilir bir karakter dizisi olan dize benzeri bir nesneyi temsil eder.

StringBuilder ile Dize türü karşılaştırması

Ve String her ikisi de karakter dizilerini temsil etmesine rağmenStringBuilder, bunlar farklı şekilde uygulanır. String sabit bir türdür. Yani, bir String nesneyi değiştirmek için görünen her işlem aslında yeni bir dize oluşturur.

Örneğin, aşağıdaki C# örneğindeki yöntemine String.Concat yapılan çağrı, adlı valuebir dize değişkeninin değerini değiştirmek için görünür. Aslında, yöntemi yöntemine Concat geçirilen nesneden value farklı bir değere ve adrese sahip bir nesne döndürürvalue. Örneğin derleyici seçeneği kullanılarak /unsafe derlenmiş olması gerektiğini unutmayın.

using System;

public class Example7
{
    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
    let mutable value = "This is the first sentence" + "."
    use start = fixed value
    value <- System.String.Concat(value, "This is the second sentence. ")
    use current = fixed value
    printfn $"{start = current}"
// The example displays the following output:
//      False

Kapsamlı dize işlemesi gerçekleştiren yordamlar için (bir dizeyi döngüde birçok kez değiştiren uygulamalar gibi), bir dizeyi tekrar tekrar değiştirmek önemli bir performans cezasına neden olabilir. Alternatif olarak, değiştirilebilir bir dize sınıfı olan öğesini kullanabilirsiniz StringBuilder. Mutability, sınıfın bir örneği oluşturulduktan sonra karakter ekleme, kaldırma, değiştirme veya ekleme yoluyla değiştirilebileceği anlamına gelir. Nesne StringBuilder , dizedeki genişletmeleri barındırmak için bir arabellek tutar. Yer varsa arabelleğe yeni veriler eklenir; aksi takdirde yeni, daha büyük bir arabellek ayrılır, özgün arabellekten veriler yeni arabelleğe kopyalanır ve yeni veriler yeni arabelleğe eklenir.

Önemli

Sınıfı genellikle sınıfından StringBuilderString daha iyi performans sunsa da, dizeleri işlemek istediğinizde ile otomatik olarak yerine başka StringStringBuilder bir değer eklememelisiniz. Performans, dizenin boyutuna, yeni dize için ayrılacak bellek miktarına, kodunuzun yürütülmekte olduğu sisteme ve işlem türüne bağlıdır. Gerçekten önemli bir performans artışı sunup sağlamadığını StringBuilder belirlemek için kodunuzu test etmeye hazırlıklı olmalısınız.

sınıfını String şu koşullar altında kullanmayı göz önünde bulundurun:

  • Kodunuzun bir dizede yapacağı değişikliklerin sayısı az olduğunda. Bu durumlarda, StringBuilder üzerinde göz ardı edilebilir veya hiçbir performans geliştirmesi Stringsunmayabilir.

  • Sabit sayıda birleştirme işlemi gerçekleştirirken, özellikle dize değişmez değerleriyle. Bu durumda, derleyici birleştirme işlemlerini tek bir işlemde birleştirebilir.

  • Dizenizi oluştururken kapsamlı arama işlemleri yapmanız gerektiğinde. sınıfında StringBuilder veya StartsWithgibi IndexOf arama yöntemleri yok. Bu işlemler için nesnesini öğesine String dönüştürmeniz StringBuilder gerekir ve bu, kullanarak StringBuilderelde edilen performans avantajını olumsuz etkileyebilir. Daha fazla bilgi için StringBuilder nesnesindeki metni arama bölümüne bakın.

sınıfını StringBuilder şu koşullar altında kullanmayı göz önünde bulundurun:

  • Kodunuzun tasarım zamanında bir dizede bilinmeyen sayıda değişiklik yapmasını beklediğiniz zaman (örneğin, kullanıcı girişi içeren rastgele sayıda dizeyi birleştirmek için bir döngü kullandığınızda).
  • Kodunuzun bir dizede önemli sayıda değişiklik yapmasını beklediğiniz durumlarda.

StringBuilder nasıl çalışır?

özelliği, StringBuilder.Length nesnenin şu anda içerdiği karakter StringBuilder sayısını gösterir. Nesneye karakter eklerseniz, nesnenin StringBuilder içerebileceği karakter sayısını tanımlayan özelliğin StringBuilder.Capacity boyutuna eşit olana kadar uzunluğu artar. Eklenen karakter sayısı nesnenin uzunluğunun StringBuilder geçerli kapasitesini aşmasına neden olursa, yeni bellek ayrılır, özelliğin Capacity değeri ikiye katlanır, nesneye StringBuilder yeni karakterler eklenir ve Length özelliği ayarlanır. Nesnesi için StringBuilder ek bellek, özelliği tarafından StringBuilder.MaxCapacity tanımlanan değere ulaşana kadar dinamik olarak ayrılır. Maksimum kapasiteye ulaşıldığında, nesne için StringBuilder başka bellek ayrılamıyor ve karakter eklemeye veya maksimum kapasitenin ötesine genişletmeye çalışmak bir ArgumentOutOfRangeException veya bir OutOfMemoryException özel durum oluşturur.

Aşağıdaki örnekte, nesneye atanan dize genişledikçe nesnenin StringBuilder yeni bellek ayırması ve kapasitesini dinamik olarak artırması gösterilmektedir. Kod, varsayılan (parametresiz) oluşturucusunu çağırarak bir StringBuilder nesne oluşturur. Bu nesnenin varsayılan kapasitesi 16 karakterdir ve maksimum kapasitesi 2 milyar karakterden fazladır. Dize uzunluğu (19 karakter) nesnenin varsayılan kapasitesini aştığı için "Bu bir tümcedir" dizesi eklendiğinde yeni bir bellek ayırması StringBuilder elde edilir. Nesnenin kapasitesi 32 karaktere iki katına çıkarır, yeni dize eklenir ve nesnenin uzunluğu artık 19 karaktere eşit olur. Kod daha sonra nesnenin değerine 11 kez "Bu ek bir cümledir" dizesini StringBuilder ekler. Ekleme işlemi nesnenin uzunluğunun StringBuilder kapasitesini aşmasına neden olduğunda, var olan kapasitesi ikiye katlanır ve Append işlem başarılı olur.

using System;
using System.Reflection;
using System.Text;

public class Example4
{
    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
open System.Text

let showSBInfo (sb: StringBuilder) =
    for prop in sb.GetType().GetProperties() do
        if prop.GetIndexParameters().Length = 0 then
            printf $"{prop.Name}: {prop.GetValue sb:N0}    "

    printfn ""

let sb = StringBuilder()
showSBInfo sb
sb.Append "This is a sentence." |> ignore
showSBInfo sb

for i = 0 to 10 do
    sb.Append "This is an additional sentence." |> ignore
    showSBInfo sb

// 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 Example5
    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ırma

Bir nesnenin StringBuilder varsayılan kapasitesi 16 karakterdir ve varsayılan kapasite üst sınırıdır Int32.MaxValue. ve oluşturucularını çağırırsanız StringBuilder()StringBuilder(String) bu varsayılan değerler kullanılır.

Bir nesnenin ilk kapasitesini StringBuilder aşağıdaki yollarla açıkça tanımlayabilirsiniz:

  • Nesnesini oluştururken parametre capacity içeren oluşturuculardan StringBuilder herhangi birini çağırarak.

  • Var olan StringBuilder bir nesneyi genişletmek için özelliğine StringBuilder.Capacity açıkça yeni bir değer atayarak. Yeni kapasite mevcut kapasiteden küçükse veya nesnenin maksimum kapasitesinden büyükse özelliğin StringBuilder bir özel durum oluşturduğunu unutmayın.

  • yöntemini yeni kapasiteyle çağırarak StringBuilder.EnsureCapacity . Yeni kapasite nesnenin maksimum kapasitesinden StringBuilder büyük olmamalıdır. Ancak, özelliğine yapılan atamadan Capacity farklı olarak, EnsureCapacity istenen yeni kapasite mevcut kapasiteden küçükse bir özel durum oluşturmaz; bu durumda yöntem çağrısının hiçbir etkisi yoktur.

Oluşturucu çağrısında nesneye StringBuilder atanan dizenin uzunluğu varsayılan kapasiteyi veya belirtilen kapasiteyi aşarsa, Capacity özellik parametresiyle belirtilen dizenin uzunluğuna value ayarlanır.

Oluşturucuyu çağırarak StringBuilder(Int32, Int32) bir StringBuilder nesnenin maksimum kapasitesini açıkça tanımlayabilirsiniz. Özelliğe salt okunur olduğundan yeni bir değer atayarak maksimum kapasiteyi MaxCapacity değiştiremezsiniz.

Önceki bölümde gösterildiği gibi, mevcut kapasite yetersiz olduğunda ek bellek ayrılır ve bir StringBuilder nesnenin kapasitesi özelliği tarafından MaxCapacity tanımlanan değere kadar iki katına çıkar.

Genel olarak, varsayılan kapasite ve maksimum kapasite çoğu uygulama için yeterlidir. Aşağıdaki koşullar altında bu değerleri ayarlamayı düşünebilirsiniz:

  • Nesnenin StringBuilder nihai boyutu genellikle birkaç megabayttan fazla olmak üzere çok fazla büyüyecekse. Bu durumda, çok fazla bellek yeniden ayırma gereksinimini ortadan kaldırmak için ilk Capacity özelliği önemli ölçüde yüksek bir değere ayarlamanın bazı performans yararları olabilir.

  • Kodunuz sınırlı belleğe sahip bir sistemde çalışıyorsa. Bu durumda, kodunuzun MaxCapacity bellek kısıtlanmış bir ortamda yürütülmesine neden olabilecek büyük dizeleri işlemesinden daha Int32.MaxValue az olarak özelliğini ayarlamayı düşünebilirsiniz.

StringBuilder nesnesi örneği oluşturma

Aşağıdaki tabloda listelenen altı aşırı yüklenmiş sınıf oluşturucusunun birini çağırarak bir StringBuilder nesne örneği oluşturursunuz. Oluşturucuların üçü, değeri boş bir dize olan ancak ve MaxCapacity değerlerini farklı ayarlayan bir StringBuilder nesnenin örneğini Capacity oluşturur. Kalan üç oluşturucu, belirli bir StringBuilder dize değerine ve kapasitesine sahip bir nesne tanımlar. Üç oluşturucudan ikisi varsayılan en yüksek kapasiteyi Int32.MaxValuekullanırken, üçüncüsü maksimum kapasiteyi ayarlamanıza olanak tanır.

Oluşturucu Dize değeri seçeneğini belirleyin Kapasite Maksimum kapasite
StringBuilder() String.Empty 16 Int32.MaxValue
StringBuilder(Int32) String.Empty parametresi tarafından capacity tanımlanır Int32.MaxValue
StringBuilder(Int32, Int32) String.Empty parametresi tarafından capacity tanımlanır parametresi tarafından maxCapacity tanımlanır
StringBuilder(String) parametresi tarafından value tanımlanır 16 veya value. Length, hangisi daha büyükse Int32.MaxValue
StringBuilder(String, Int32) parametresi tarafından value tanımlanır veya valueparametresi tarafından capacity tanımlanır. Length, hangisi daha büyükse. Int32.MaxValue
StringBuilder(String, Int32, Int32, Int32) tarafından valuetanımlanır. Substring(startIndex, length) veya valueparametresi tarafından capacity tanımlanır. Length, hangisi daha büyükse. Int32.MaxValue

Aşağıdaki örnek, nesnelerin örneğini StringBuilder oluşturmak için bu oluşturucu aşırı yüklemelerinden üç tane kullanır.

using System;
using System.Text;

public class Example8
{
    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
open System.Text

let showSBInfo (sb: StringBuilder) =
    for prop in sb.GetType().GetProperties() do
        if prop.GetIndexParameters().Length = 0 then
            printf $"{prop.Name}: {prop.GetValue sb:N0}    "

    printfn ""

let value = "An ordinary string"
let index = value.IndexOf "An " + 3
let capacity = 0xFFFF

// Instantiate a StringBuilder from a string.
let sb1 = StringBuilder value
showSBInfo sb1

// Instantiate a StringBuilder from string and define a capacity.
let sb2 = StringBuilder(value, capacity)
showSBInfo sb2

// Instantiate a StringBuilder from substring and define a capacity.
let sb3 = StringBuilder(value, index, value.Length - index, capacity)
showSBInfo sb3

// 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 Example8
    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ğırma

Bir StringBuilder örnekteki dizeyi değiştiren yöntemlerin çoğu aynı örneğe başvuru döndürür. Bu, yöntemleri iki şekilde çağırmanızı StringBuilder sağlar:

  • Aşağıdaki örnekte olduğu gibi tek tek yöntem çağrıları yapabilir ve dönüş değerini yoksayabilirsiniz.

    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.
    
    open System.Text
    
    let sb = StringBuilder()
    sb.Append "This is the beginning of a sentence, " |> ignore
    sb.Replace("the beginning of ", "") |> ignore
    sb.Insert((string sb).IndexOf "a " + 2, "complete ") |> ignore
    sb.Replace(",", ".") |> ignore
    printfn $"{sb}"
    // The example displays the following output:
    //        This is a complete sentence.
    
    Imports System.Text
    
    Module Example2
        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 deyimde bir dizi yöntem çağrısı yapabilirsiniz. Ardışık işlemleri zincirleyen tek bir deyim yazmak istiyorsanız bu kullanışlı olabilir. Aşağıdaki örnek, önceki örnekteki üç yöntem çağrısını tek bir kod satırında birleştirir.

    using System;
    using System.Text;
    
    public class Example2
    {
        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.
    
    open System.Text
    
    let sb = StringBuilder "This is the beginning of a sentence, "
    
    sb
        .Replace("the beginning of ", "")
        .Insert((string sb).IndexOf "a " + 2, "complete ")
        .Replace(",", ".")
    |> ignore
    
    printfn $"{sb}"
    // The example displays the following output:
    //        This is a complete sentence.
    
    Imports System.Text
    
    Module Example3
        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ştirme

Bir nesnedeki StringBuilder karakterleri StringBuilder yinelemek, eklemek, silmek veya değiştirmek için sınıfının yöntemlerini kullanabilirsiniz.

StringBuilder karakterlerini yineleme

özelliğini kullanarak bir StringBuilder nesnedeki karakterlere StringBuilder.Chars[] erişebilirsiniz. C# Chars[] dilinde bir dizin oluşturucudur; Visual Basic'te sınıfın StringBuilder varsayılan özelliğidir. Bu, özelliğine açıkça başvurmadan yalnızca dizinlerini kullanarak tek tek karakterleri ayarlamanıza veya almanıza Chars[] olanak tanır. Nesnedeki StringBuilder karakterler 0 (sıfır) dizininden başlar ve - 1 dizinine Length devam edin.

Aşağıdaki örnekte özelliği gösterilmektedir Chars[] . Nesneye StringBuilder on rastgele sayı ekler ve her karakteri yineler. Karakterin Unicode kategorisi ise UnicodeCategory.DecimalDigitNumber, sayıyı 1 azaltır (veya değeri 0 ise sayıyı 9 olarak değiştirir). Örnekte, tek tek karakterlerin StringBuilder değerleri değiştirilmeden önce ve sonra nesnenin içeriği görüntülenir.

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

public class Example3
{
    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
open System
open System.Globalization
open System.Text

let rnd = Random()
let sb = new StringBuilder()

// Generate 10 random numbers and store them in a StringBuilder.
for _ = 0 to 9 do
    rnd.Next().ToString "N5" |> sb.Append |> ignore

printfn "The original string:"
printfn $"{sb}"

// Decrease each number by one.
for i = 0 to sb.Length - 1 do
    if Char.GetUnicodeCategory(sb[i]) = UnicodeCategory.DecimalDigitNumber then
        let number = Char.GetNumericValue sb.[i] |> int
        let number = number - 1
        let number = if number < 0 then 9 else number
        sb.[i] <- number.ToString()[0]

printfn "\nThe new string:"
printfn $"{sb}"

// 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 Example4
    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ğiyle karakter tabanlı dizin oluşturmanın Chars[] kullanılması aşağıdaki koşullar altında son derece yavaş olabilir:

Her karakter erişimi, dizine alınacak doğru arabelleği bulmak için bağlantılı öbek listesinin tamamını gösterdiğinden performans ciddi ölçüde etkilenir.

Not

Büyük bir "öbekli" StringBuilder nesne için bile, bir veya az sayıda karaktere dizin tabanlı erişim için özelliğinin kullanılması Chars[] göz ardı edilebilir bir performans etkisine sahiptir; genellikle bu bir O(n) işlemidir. Önemli performans etkisi, nesnedeki StringBuilder karakterleri yinelerken (O (n^2) işlemidir.

Nesnelerle karakter tabanlı dizin oluşturma kullanırken performans sorunlarıyla StringBuilder karşılaşırsanız, aşağıdaki geçici çözümlerden herhangi birini kullanabilirsiniz:

  • StringBuilder yöntemini çağırarak örneği bir'e String dönüştürünToString, ardından dizedeki karakterlere erişin.

  • Varolan StringBuilder nesnenin içeriğini önceden boyutlandırılmış StringBuilder yeni bir nesneye kopyalayın. Yeni StringBuilder nesne öbekli olmadığından performans artar. Örneğin:

    // 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 StringBuilder ilk kapasitesini yaklaşık olarak beklenen en büyük boyutuna eşit bir değere StringBuilder(Int32) ayarlayın. Bunun, en yüksek kapasiteye nadiren ulaşsa StringBuilder bile bellek bloğunun tamamını ayırdığını unutmayın.

StringBuilder nesnesine metin ekleme

sınıfı, StringBuilder bir StringBuilder nesnenin içeriğini genişletmek için aşağıdaki yöntemleri içerir:

  • Append yöntemi bir dizeyi, alt dizeyi, karakter dizisini, karakter dizisinin bir bölümünü, birden çok kez tekrarlanan tek bir karakteri veya ilkel veri türünün dize gösterimini bir StringBuilder nesneye ekler.

  • yöntemi, AppendLine bir nesneye bir satır sonlandırıcı veya bir dize ile birlikte bir satır sonlandırıcı ekler StringBuilder .

  • yöntemi bir AppendFormat nesneye StringBuilder bileşik biçim dizesi ekler. Sonuç dizesine dahil edilen nesnelerin dize gösterimleri, geçerli sistem kültürünün veya belirtilen kültürün biçimlendirme kurallarını yansıtabilir.

  • Insert yöntemi bir dizeyi, alt dizeyi, bir dizenin birden çok yinelemesini, karakter dizisini, karakter dizisinin bir bölümünü veya ilkel veri türünün dize gösterimini nesnede StringBuilder belirtilen bir konuma ekler. Konum sıfır tabanlı bir dizin tarafından tanımlanır.

Aşağıdaki örnek, bir nesnenin Appendmetnini genişletmek için , AppendLine, AppendFormatve Insert yöntemlerini kullanır.StringBuilder

using System;
using System.Text;

public class Example6
{
    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            <
open System
open System.Text

// Create a StringBuilder object with no text.
let sb = StringBuilder()
// Append some text.
sb
    .Append('*', 10)
    .Append(" Adding Text to a StringBuilder Object ")
    .Append('*', 10)
|> ignore

sb.AppendLine "\n" |> ignore
sb.AppendLine "Some code points and their corresponding characters:" |> ignore
// Append some formatted text.
for i = 50 to 60 do
    sb.AppendFormat("{0,12:X4} {1,12}", i, Convert.ToChar i) |> ignore
    sb.AppendLine() |> ignore

// Find the end of the introduction to the column.
let pos = (string sb).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"))
|> ignore

// Convert the StringBuilder to a string and display it.
printfn $"{sb}"


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

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

StringBuilder nesnesinden metin silme

sınıfı, StringBuilder geçerli StringBuilder örneğin boyutunu azaltabilecek yöntemler içerir. Clear yöntemi tüm karakterleri kaldırır ve özelliğini sıfır olarak ayarlarLength. yöntemi, Remove belirli bir dizin konumundan başlayarak belirtilen sayıda karakteri siler. Ayrıca, özelliğini geçerli örneğin uzunluğundan StringBuilder daha küçük bir değere ayarlayarak Length nesnenin sonundaki karakterleri kaldırabilirsiniz.

Aşağıdaki örnek bir nesneden metnin bir StringBuilder bölümünü kaldırır, sonuçta elde edilen kapasite, maksimum kapasite ve uzunluk özellik değerlerini görüntüler ve ardından nesnedeki StringBuilder tüm karakterleri kaldırmak için yöntemini çağırırClear.

using System;
using System.Text;

public class Example5
{
    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
open System.Text

let showSBInfo (sb: StringBuilder) =
    for prop in sb.GetType().GetProperties() do
        if prop.GetIndexParameters().Length = 0 then
            printf $"{prop.Name}: {prop.GetValue sb:N0}    "

    printfn ""

let sb = StringBuilder "A StringBuilder object"
showSBInfo sb
// Remove "object" from the text.
let textToRemove = "object"
let pos = (string sb).IndexOf textToRemove

if pos >= 0 then
    sb.Remove(pos, textToRemove.Length) |> ignore
    showSBInfo sb

// Clear the StringBuilder contents.
sb.Clear() |> ignore
showSBInfo sb

// 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 Example6
    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 Then
            sb.Remove(pos, textToRemove.Length)
            ShowSBInfo(sb)
        End If
        ' Clear the StringBuilder contents.
        sb.Clear()
        ShowSBInfo(sb)
    End Sub

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

StringBuilder nesnesindeki metni değiştirme

yöntemi, StringBuilder.Replace bir karakterin veya dizenin nesnenin tamamında veya belirli bir karakter aralığındaki tüm StringBuilder oluşumlarının yerini alır. Aşağıdaki örnek, nesnedeki Replace tüm ünlem işaretlerini (!) soru işaretleri (?) StringBuilder ile değiştirmek için yöntemini kullanır.

using System;
using System.Text;

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

let myStringBuilder = StringBuilder "Hello World!"
myStringBuilder.Replace('!', '?') |> ignore
printfn $"{myStringBuilder}"

// The example displays the following output:
//       Hello World?
Imports System.Text

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

StringBuilder nesnesindeki metni arama

sınıfı, StringBuilder sınıfı tarafından String sağlanan , String.IndexOfve yöntemlerine String.Containsbenzer yöntemler içermez. String.StartsWith Bu yöntem, nesnede belirli bir karakter veya alt dize için arama yapmanızı sağlar. Bir alt dizenin iletişim durumunu veya başlangıç karakteri konumunu belirlemek için bir String dize arama yöntemi veya normal ifade yöntemi kullanarak bir değerde aramanız gerekir. Aşağıdaki tabloda gösterildiği gibi, bu tür aramaları uygulamanın dört yolu vardır.

Teknik Avantajlar Dezavantajlar
Dize değerlerini nesneye StringBuilder eklemeden önce arayın. Bir alt dizenin mevcut olup olmadığını belirlemek için kullanışlıdır. Bir alt dizenin dizin konumu önemli olduğunda kullanılamaz.
Döndürülen String nesneyi çağırın ToString ve arayın. Tüm metni bir StringBuilder nesneye atar ve sonra değiştirmeye başlarsanız kullanımı kolaydır. Nesneye tüm metinler eklenmeden önce değişiklik yapmanız gerekiyorsa sürekli çağrı ToString yapmak StringBuilder zahmetli.

Değişiklik yapıyorsanız nesne metninin StringBuilder sonundan çalışmayı unutmayın.
Chars[] Bir karakter aralığını sıralı olarak aramak için özelliğini kullanın. Tek tek karakterlerle veya küçük bir alt dizeyle ilgileniyorsanız kullanışlıdır. Aranacak karakter sayısı büyükse veya arama mantığı karmaşıksa hantal.

Yinelenen yöntem çağrıları ile çok büyük olan nesneler için çok düşük performans elde eder.
StringBuilder Nesnesini bir String nesneye dönüştürün ve nesne üzerinde String değişiklikler yapın. Değişiklik sayısı azsa kullanışlıdır. Değişiklik sayısı büyükse sınıfın StringBuilder performans avantajını olumsuzlar.

Şimdi bu teknikleri daha ayrıntılı inceleyelim.

  • Aramanın amacı belirli bir alt dizenin var olup olmadığını belirlemekse (yani alt dizenin konumuyla ilgilenmiyorsanız), dizeleri nesnede StringBuilder depolamadan önce arayabilirsiniz. Aşağıdaki örnek olası bir uygulama sağlar. Oluşturucusunun bir StringBuilderFinder nesneye ve dizede bulunacak alt dizeye StringBuilder bir başvuru geçirildiğini bir sınıf tanımlar. Bu durumda örnek, kaydedilen sıcaklıkların Fahrenheit mi yoksa Santigrat mı olduğunu belirlemeye çalışır ve nesnenin StringBuilder başına uygun giriş metnini ekler. Rastgele sayı oluşturucu, santigrat derece veya Fahrenheit derecelerinde veri içeren bir diziyi seçmek için kullanılır.

    using System;
    using System.Text;
    
    public class Example9
    {
        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
    
    open System
    open System.Text
    
    type StringBuilderFinder(sb: StringBuilder, textToFind: string) =
        member _.SearchAndAppend(stringToSearch: string) =
            sb.Append stringToSearch |> ignore
            stringToSearch.Contains textToFind
    
    let tempF = [| "47.6F"; "51.3F"; "49.5F"; "62.3F" |]
    let tempC = [| "21.2C"; "16.1C"; "23.5C"; "22.9C" |]
    let temps = [| tempF; tempC |]
    
    let sb = StringBuilder()
    let f = StringBuilderFinder(sb, "F")
    let temperatures = temps[Random.Shared.Next(2)]
    let mutable baseDate = DateTime(2013, 5, 1)
    let mutable isFahrenheit = false
    
    for temperature in temperatures do
        if isFahrenheit then
            sb.AppendFormat("{0:d}: {1}\n", baseDate, temperature) |> ignore
        else
            isFahrenheit <- $"{baseDate:d}: {temperature}\n" |> f.SearchAndAppend
    
        baseDate <- baseDate.AddDays 1
    
    if isFahrenheit then
        sb.Insert(0, "Average Daily Temperature in Degrees Fahrenheit") |> ignore
        sb.Insert(47, "\n\n") |> ignore
    
    else
        sb.Insert(0, "Average Daily Temperature in Degrees Celsius") |> ignore
        sb.Insert(44, "\n\n") |> ignore
    
    printfn $"{sb}"
    
    // 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 Example9
        Public Sub Main()
            Dim rnd As New Random()
            Dim tempF() As String = {"47.6F", "51.3F", "49.5F", "62.3F"}
            Dim tempC() As String = {"21.2C", "16.1C", "23.5C", "22.9C"}
            Dim temps()() As String = {tempF, tempC}
    
            Dim sb As StringBuilder = New StringBuilder()
            Dim f As New StringBuilderFinder(sb, "F")
            Dim baseDate As New DateTime(2013, 5, 1)
            Dim temperatures() As String = temps(rnd.Next(2))
            Dim isFahrenheit As Boolean = False
            For Each temperature In temperatures
                If isFahrenheit Then
                    sb.AppendFormat("{0:d}: {1}{2}", baseDate, temperature, vbCrLf)
                Else
                    isFahrenheit = f.SearchAndAppend(String.Format("{0:d}: {1}{2}",
                                                 baseDate, temperature, vbCrLf))
                End If
                baseDate = baseDate.AddDays(1)
            Next
            If isFahrenheit Then
                sb.Insert(0, "Average Daily Temperature in Degrees Fahrenheit")
                sb.Insert(47, vbCrLf + vbCrLf)
            Else
                sb.Insert(0, "Average Daily Temperature in Degrees Celsius")
                sb.Insert(44, vbCrLf + vbCrLf)
            End If
            Console.WriteLine(sb.ToString())
        End Sub
    End Module
    
    Public Class StringBuilderFinder
       Private sb As StringBuilder
       Private text As String
       
       Public Sub New(sb As StringBuilder, textToFind As String)
          Me.sb = sb
          text = textToFind
       End Sub
       
       Public Function SearchAndAppend(stringToSearch As String) As Boolean
          sb.Append(stringToSearch)
          Return stringToSearch.Contains(text)
       End Function
    End Class
    ' The example displays output similar to the following:
    '    Average Daily Temperature in Degrees Celsius
    '    
    '    5/1/2013: 21.2C
    '    5/2/2013: 16.1C
    '    5/3/2013: 23.5C
    '    5/4/2013: 22.9C
    
  • StringBuilder.ToString nesnesini bir String nesneye dönüştürmek StringBuilder için yöntemini çağırın. veya String.StartsWithgibi String.LastIndexOf yöntemleri kullanarak dizede arama yapabilir veya desenleri aramak için normal ifadeleri ve Regex sınıfı kullanabilirsiniz. Hem hem de StringBuilderString nesneler karakterleri depolamak için UTF-16 kodlaması kullandığından, karakterlerin, alt dizelerin ve normal ifade eşleşmelerinin dizin konumları her iki nesnede de aynıdır. Bu, nesnede metnin bulunduğu konumda değişiklik yapmak için yöntemleri kullanmanıza StringBuilderString olanak tanır.

    Not

    Bu yaklaşımı benimserseniz, nesneyi tekrar tekrar bir dizeye dönüştürmeniz gerekmemesi için nesnenin sonundan StringBuilderStringBuilder başına kadar çalışmanız gerekir.

    Aşağıdaki örnek bu yaklaşımı gösterir. İngilizce alfabenin her harfinin dört oluşumunu bir StringBuilder nesnede depolar. Ardından metni bir String nesneye dönüştürür ve her dört karakterlik dizinin başlangıç konumunu belirlemek için normal bir ifade kullanır. Son olarak, ilk sıra dışında her dört karakterlik diziden önce bir alt çizgi ekler ve dizinin ilk karakterini büyük harfe dönüştürür.

    using System;
    using System.Text;
    using System.Text.RegularExpressions;
    
    public class Example10
    {
        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
    
    open System
    open System.Text
    open System.Text.RegularExpressions
    
    // Create a StringBuilder object with 4 successive occurrences
    // of each character in the English alphabet.
    let sb = StringBuilder()
    
    for char in 'a' .. 'z' do
        sb.Append(char, 4) |> ignore
    
    // Create a parallel string object.
    let sbString = string sb
    // Determine where each new character sequence begins.
    let pattern = @"(\w)\1+"
    let matches = Regex.Matches(sbString, pattern)
    
    // Uppercase the first occurrence of the sequence, and separate it
    // from the previous sequence by an underscore character.
    for i = matches.Count - 1 downto 0 do
        let m = matches[i]
        sb[m.Index] <- Char.ToUpper sb[m.Index]
    
        if m.Index > 0 then
            sb.Insert(m.Index, "_") |> ignore
    
    // Display the resulting string.
    let sbString2 = string sb
    
    for line = 0 to (sbString2.Length - 1) / 80 do
        let nChars =
            if line * 80 + 79 <= sbString2.Length then
                80
            else
                sbString2.Length - line * 80
    
        printfn $"{sbString2.Substring(line * 80, nChars)}"
    
    
    // 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 Example10
        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
    
  • Bir nesnedeki StringBuilder.Chars[] karakter StringBuilder aralığını sıralı olarak aramak için özelliğini kullanın. Aranacak karakter sayısı büyükse veya arama mantığı özellikle karmaşıksa bu yaklaşım pratik olmayabilir. Çok büyük, öbeklenmiş StringBuilder nesneler için karakter karakter dizin tabanlı erişimin performans üzerindeki etkileri için özelliğin belgelerine StringBuilder.Chars[] bakın.

    Aşağıdaki örnek, önceki örnekle aynı işleve sahiptir ancak uygulama açısından farklılık gösterir. Bir karakter değerinin Chars[] ne zaman 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.

    using System;
    using System.Text;
    
    public class Example11
    {
        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
    
    open System
    open System.Text
    
    // Create a StringBuilder object with 4 successive occurrences
    // of each character in the English alphabet.
    let sb = StringBuilder()
    
    for char in 'a' .. 'z' do
        sb.Append(char, 4) |> ignore
    
    // Iterate the text to determine when a new character sequence occurs.
    let mutable position = 0
    let mutable current = '\u0000'
    
    while position <= sb.Length - 1 do
        if sb[position] <> current then
            current <- sb[position]
            sb[position] <- Char.ToUpper sb[position]
    
            if position > 0 then
                sb.Insert(position, "_") |> ignore
    
            position <- position + 2
    
        else
            position <- position + 1
    
    // Display the resulting string.
    let sbString = string sb
    
    for line = 0 to (sbString.Length - 1) / 80 do
        let nChars =
            if line * 80 + 79 <= sbString.Length then
                80
            else
                sbString.Length - line * 80
    
        printfn $"{sbString.Substring(line * 80, nChars)}"
    
    // 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 Example11
        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
    
  • Nesnede StringBuilder değiştirilmemiş tüm metni depolayın, nesnesini bir String nesneye dönüştürmek için yöntemini çağırın StringBuilder.ToStringStringBuilder ve nesne üzerinde değişiklikleri gerçekleştirinString. Yalnızca birkaç değişikliğiniz varsa bu yaklaşımı kullanabilirsiniz; aksi takdirde sabit dizelerle çalışma maliyeti, nesne StringBuilder kullanmanın performans avantajlarını olumsuz etkileyebilir.

    Aşağıdaki örnek, önceki iki örnekle aynı işleve sahiptir ancak uygulama açısından farklılık gösterir. Bir StringBuilder nesne oluşturur, nesneyi bir String nesneye dönüştürür ve sonra dizede kalan tüm değişiklikleri gerçekleştirmek için normal bir ifade kullanır. yöntemi, Regex.Replace(String, String, MatchEvaluator) her eşleşmede değiştirme gerçekleştirmek için bir lambda ifadesi kullanır.

    using System;
    using System.Text;
    using System.Text.RegularExpressions;
    
    public class Example12
    {
        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
    
    open System.Text
    open System.Text.RegularExpressions
    
    // Create a StringBuilder object with 4 successive occurrences
    // of each character in the English alphabet.
    let sb = StringBuilder()
    
    for char in 'a' .. 'z' do
        sb.Append(char, 4) |> ignore
    
    // Convert it to a string.
    let sbString = string sb
    
    // Use a regex to uppercase the first occurrence of the sequence,
    // and separate it from the previous sequence by an underscore.
    let pattern = @"(\w)(\1+)"
    
    let sbStringReplaced =
        Regex.Replace(
            sbString,
            pattern,
            fun m ->
                (if m.Index > 0 then "_" else "")
                + m.Groups[ 1 ].Value.ToUpper()
                + m.Groups[2].Value
        )
    
    // Display the resulting string.
    for line = 0 to (sbStringReplaced.Length - 1) / 80 do
        let nChars =
            if line * 80 + 79 <= sbStringReplaced.Length then
                80
            else
                sbStringReplaced.Length - line * 80
    
        printfn $"{sbStringReplaced.Substring(line * 80, nChars)}"
    
    // 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 Example12
        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ürme

Nesnesi tarafından StringBuilderStringBuilder temsil edilen dizeyi parametresi olan bir String yönteme geçirebilmeniz veya kullanıcı arabiriminde görüntüleyebilmeniz için önce nesneyi bir String nesneye dönüştürmeniz gerekir. Yöntemini çağırarak bu dönüştürmeyi StringBuilder.ToString gerçekleştirirsiniz. Bir çizim için, bir nesneyi normal ifade yöntemine geçirebilmek için dizeye StringBuilder dönüştürmek için yöntemini çağıran ToString önceki örne bakın.