StringBuilder クラス

定義

可変型の文字列を表します。 このクラスは継承できません。

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
継承
StringBuilder
属性
実装

次の例は、 クラスで定義されているメソッドの多くを呼び出す方法を StringBuilder 示しています。

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
open System.Text

// Create a StringBuilder that expects to hold 50 characters.
// Initialize the StringBuilder with "ABC".
let sb = StringBuilder("ABC", 50)

// Append three characters (D, E, and F) to the end of the StringBuilder.
sb.Append [| 'D'; 'E'; 'F' |] |> ignore

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

// Display the number of characters in the StringBuilder and its string.
printfn $"{sb.Length} chars: {sb}"

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

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

// Display the number of characters in the StringBuilder and its string.
printfn $"{sb.Length} chars: {sb}"

// 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

注釈

このクラスは、値が変更可能な一連の文字である文字列に似たオブジェクトを表します。

このセクションの内容は次のとおりです。

String 型と StringBuilder 型

String の両方がStringBuilder文字のシーケンスを表しますが、実装方法は異なります。 String は不変型です。 つまり、オブジェクトを変更するように見える各操作は String 、実際には新しい文字列を作成します。

たとえば、次の C# の例の メソッドの String.Concat 呼び出しは、 という名前 valueの文字列変数の値を変更するように見えます。 実際、メソッドは、メソッドにConcat渡されたオブジェクトとは異なる値とアドレスをvalue持つオブジェクトを返valueします。 この例はコンパイラ オプションを使用してコンパイルする /unsafe 必要があることに注意してください。

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
    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

広範な文字列操作を実行するルーチン (ループ内で文字列を何度も変更するアプリなど) の場合、文字列を繰り返し変更すると、パフォーマンスが大幅に低下する可能性があります。 もう 1 つの方法は、 を使用 StringBuilderすることです。これは変更可能な文字列クラスです。 変更可能性とは、クラスのインスタンスが作成されると、文字の追加、削除、置換、または挿入によって変更できることを意味します。 オブジェクトは StringBuilder 、文字列の拡張に対応するバッファーを保持します。 会議室が使用可能な場合は、新しいデータがバッファーに追加されます。それ以外の場合は、新しい大きなバッファーが割り当てられ、元のバッファーのデータが新しいバッファーにコピーされ、新しいデータが新しいバッファーに追加されます。

重要

クラスはStringBuilder通常、 クラスよりも優れたパフォーマンスをString提供しますが、文字列を操作する場合は、 を に自動的に置き換えるStringStringBuilderべきではありません。 パフォーマンスは、文字列のサイズ、新しい文字列に割り当てられるメモリの量、コードが実行されているシステム、操作の種類によって異なります。 実際にパフォーマンスが大幅に向上するかどうかを StringBuilder 判断するために、コードをテストする準備が必要です。

次の条件で クラスを String 使用することを検討してください。

  • コードが文字列に加える変更の数が少ない場合。 このような場合、 StringBuilder では、 に比して Stringごくわずかか、またはパフォーマンスが向上しない可能性があります。

  • 固定数の連結操作 (特に文字列リテラルを使用) を実行する場合。 この場合、コンパイラは連結操作を 1 つの操作に結合する可能性があります。

  • 文字列の構築中に広範な検索操作を実行する必要がある場合。 クラスにはStringBuilder、 や StartsWithなどのIndexOf検索メソッドがありません。 これらの操作では オブジェクトを StringBuilder に変換する String 必要があります。これにより、 を使用 StringBuilderするとパフォーマンス上の利点が否定される可能性があります。 詳細については、「 StringBuilder オブジェクト内のテキストを検索する 」セクションを参照してください。

次の条件で クラスを StringBuilder 使用することを検討してください。

  • コードがデザイン時に文字列に不明な数の変更を加えると予想される場合 (たとえば、ループを使用してユーザー入力を含む文字列のランダムな数を連結する場合)。

  • コードが文字列に対してかなりの数の変更を加えると予想される場合。

StringBuilder のしくみ

プロパティは StringBuilder.Length 、オブジェクトに現在含まれている文字数を StringBuilder 示します。 オブジェクトに文字を StringBuilder 追加すると、オブジェクトに含めることができる文字数を定義する プロパティの StringBuilder.Capacity サイズと等しくなるまで、その長さが長くなります。 追加された文字数によってオブジェクトの長さが現在の StringBuilder 容量を超える場合、新しいメモリが割り当てられ、プロパティの Capacity 値が 2 倍になり、新しい文字がオブジェクトに StringBuilder 追加され、その Length プロパティが調整されます。 オブジェクトの StringBuilder 追加メモリは、 プロパティで定義された値に達するまで動的に StringBuilder.MaxCapacity 割り当てられます。 最大容量に達すると、オブジェクトにそれ以上メモリを StringBuilder 割り当てることができなくなり、文字を追加したり、最大容量を超えて拡張しようとすると、 ArgumentOutOfRangeException または OutOfMemoryException 例外がスローされます。

次の例は、オブジェクトが新しいメモリを StringBuilder 割り当て、オブジェクトに割り当てられた文字列が拡張されると容量を動的に増やす方法を示しています。 このコードでは、既定の StringBuilder (パラメーターなしの) コンストラクターを呼び出して オブジェクトを作成します。 このオブジェクトの既定の容量は 16 文字で、最大容量は 20 億文字を超えています。 文字列 "This is a sentence" を追加すると、文字列の長さ (19 文字) がオブジェクトの既定の容量を超えるので、新しいメモリ割 StringBuilder り当てが行われます。 オブジェクトの容量が 2 倍の 32 文字になり、新しい文字列が追加され、オブジェクトの長さが 19 文字になりました。 次に、文字列 "This is an additional sentence" をオブジェクトの StringBuilder 値に 11 回追加します。 追加操作によってオブジェクトの長さが容量を StringBuilder 超えるたびに、既存の容量が 2 倍になり、操作が Append 成功します。

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
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 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

メモリ割り当て

オブジェクトの既定の StringBuilder 容量は 16 文字で、既定の最大容量は です Int32.MaxValue。 これらの既定値は、 コンストラクターと StringBuilder(String) コンストラクターを呼び出す場合にStringBuilder()使用されます。

オブジェクトの初期容量は、次の StringBuilder 方法で明示的に定義できます。

  • オブジェクトの作成時に パラメーターを StringBuilder 含む capacity コンストラクターのいずれかを呼び出します。

  • プロパティに新しい値を明示的に割り当てて、既存StringBuilderStringBuilder.Capacityオブジェクトを展開します。 新しい容量が既存の容量より小さいか、オブジェクトの最大容量より大きい場合、プロパティは例外を StringBuilder スローします。

  • 新しい容量を使用して StringBuilder.EnsureCapacity メソッドを呼び出す。 新しい容量は、オブジェクトの StringBuilder 最大容量を超えてはなりません。 ただし、 プロパティへの Capacity 割り当てとは異なり、 EnsureCapacity 目的の新しい容量が既存の容量より小さい場合は例外はスローされません。この場合、メソッド呼び出しは無効です。

コンストラクター呼び出しで オブジェクトに StringBuilder 割り当てられた文字列の長さが既定の容量または指定された容量を超える場合、 Capacity プロパティは パラメーターで value 指定された文字列の長さに設定されます。

コンストラクターを呼び出すことで、オブジェクトの最大容量を StringBuilder 明示的に StringBuilder(Int32, Int32) 定義できます。 プロパティに新しい値を割り当てることで最大容量を MaxCapacity 変更することはできません。これは読み取り専用であるためです。

前のセクションで示したように、既存の容量が不十分な場合は常に、追加のメモリが割り当てられ、オブジェクトの StringBuilder 容量が プロパティによって定義された MaxCapacity 値まで倍になります。

一般に、既定の容量と最大容量は、ほとんどのアプリに適しています。 これらの値は、次の条件で設定することを検討してください。

  • オブジェクトの StringBuilder 最終的なサイズが非常に大きくなる可能性が高い場合 (通常は数メガバイトを超えます)。 この場合、初期 Capacity プロパティを大幅に高い値に設定すると、メモリの再割り当てを多くする必要がなくなり、パフォーマンス上の利点が得られる場合があります。

  • メモリが限られているシステムでコードが実行されている場合。 この場合、メモリ制約のある環境で実行される可能性のある大きな文字列をコードが処理している場合は、 プロパティを よりInt32.MaxValue小さく設定MaxCapacityすることを検討してください。

StringBuilder オブジェクトのインスタンス化

オブジェクトを StringBuilder インスタンス化する場合は、次の表に示す 6 つのオーバーロードされたクラス コンストラクターのいずれかを呼び出します。 3 つのコンストラクターは、値が空の文字列であるオブジェクトをインスタンス化 StringBuilder しますが、その Capacity 値と MaxCapacity 値の設定は異なります。 残りの 3 つのコンストラクターは、特定の StringBuilder 文字列値と容量を持つ オブジェクトを定義します。 3 つのコンストラクターのうち 2 つでは、既定の最大容量 である Int32.MaxValueを使用しますが、3 つ目のコンストラクターでは最大容量を設定できます。

コンストラクター 文字列値 容量 最大容量
StringBuilder() String.Empty 16 Int32.MaxValue
StringBuilder(Int32) String.Empty パラメーターによって定義されますcapacity Int32.MaxValue
StringBuilder(Int32, Int32) String.Empty パラメーターによって定義されますcapacity パラメーターによって定義されますmaxCapacity
StringBuilder(String) パラメーターによって定義されますvalue 16 または valueLengthのいずれか大きい方 Int32.MaxValue
StringBuilder(String, Int32) パラメーターによって定義されますvalue パラメーターまたは valueによって定義されますcapacityLengthのいずれか大きい方。 Int32.MaxValue
StringBuilder(String, Int32, Int32, Int32) value によって定義されます。 Substring(startIndex, length) パラメーターまたは valueによって定義されますcapacityLengthのいずれか大きい方。 Int32.MaxValue

次の例では、これらのコンストラクター オーバーロードのうち 3 つを使用してオブジェクトをインスタンス化 StringBuilder します。

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
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 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 メソッドの呼び出し

インスタンス内の文字列を変更するほとんどのメソッドは、 StringBuilder その同じインスタンスへの参照を返します。 これにより、次の 2 つの方法でメソッドを呼び出す StringBuilder ことができるようになります。

  • 次の例のように、個々のメソッド呼び出しを行い、戻り値を無視できます。

    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 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.
    
  • 1 つのステートメントで一連のメソッド呼び出しを行うことができます。 これは、連続する操作をチェーンする 1 つのステートメントを記述する場合に便利です。 次の例では、前の例の 3 つのメソッド呼び出しを 1 行のコードに統合します。

    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.
    
    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 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 操作の実行

クラスの メソッドを使用して、オブジェクト内StringBuilderStringBuilder文字を反復処理、追加、削除、または変更できます。

StringBuilder 文字の反復処理

オブジェクト内の文字には、 プロパティを StringBuilder 使用 StringBuilder.Chars[] してアクセスできます。 C# では、 Chars[] はインデクサーです。Visual Basic では、 クラスの既定の StringBuilder プロパティです。 これにより、プロパティを明示的に参照することなく、インデックスのみを使用して個々の文字を Chars[] 設定または取得できます。 オブジェクト内の文字は StringBuilder 、インデックス 0 (ゼロ) から始まり、インデックス Length - 1 に進みます。

次の例は、 プロパティを Chars[] 示しています。 オブジェクトに 10 個の乱数を StringBuilder 追加し、各文字を反復処理します。 文字の Unicode カテゴリが の場合は、数値が UnicodeCategory.DecimalDigitNumber1 だけ減少します (値が 0 の場合は 9 に変更されます)。 この例では、個々の文字の値が StringBuilder 変更される前と後の両方で、オブジェクトの内容を表示します。

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

Chars[] プロパティで文字ベースのインデックス付けを使用すると、次の条件下では非常に遅くなることがあります。

  • StringBuilder インスタンスが大きい (たとえば、数万文字が含まれている)。
  • StringBuilder "分厚い" です。つまり、 などの StringBuilder.Append メソッドの呼び出しが繰り返されると、オブジェクトの StringBuilder.Capacity プロパティが自動的に拡張され、新しいメモリ チャンクが割り当てられます。

文字にアクセスするたびに、チャンクのリンク リスト全体が走査されて、インデックスを付ける適切なバッファーが検索されるため、パフォーマンスが著しく低下します。

注意

大きな "チャンキー" StringBuilder オブジェクトの場合でも、1 つまたは少数の文字へのインデックスベースのアクセスに プロパティを使用 Chars[] すると、パフォーマンスへの影響はごくわずかです。通常は O(n) 操作です。 StringBuilder オブジェクト内の文字を反復処理するときは、パフォーマンスに大きな影響が発生します。これは、O(n^2) 操作でます。

StringBuilder オブジェクトで文字ベースのインデックス付けを使うときにパフォーマンスの問題が発生する場合は、次のいずれかの回避策を使うことができます。

  • ToString メソッドを呼び出して StringBuilder インスタンスを String に変換した後、文字列内の文字にアクセスします。

  • 既存の StringBuilder オブジェクトの内容を、事前にサイズを設定した新しい StringBuilder オブジェクトにコピーします。 新しい StringBuilder オブジェクトはチャンク化していないため、パフォーマンスが向上します。 次に例を示します。

    // sbOriginal is the existing StringBuilder object
    var sbNew = new StringBuilder(sbOriginal.ToString(), sbOriginal.Length);
    
    ' sbOriginal is the existing StringBuilder object
    Dim sbNew = New StringBuilder(sbOriginal.ToString(), sbOriginal.Length)
    
  • StringBuilder(Int32) コンストラクターを呼び出して、StringBuilder オブジェクトの初期容量を、予想される最大サイズにほぼ等しい値に設定します。 このようにすると、StringBuilder が最大容量に達することがほとんどない場合であっても、メモリ ブロック全体が割り当てられることに注意してください。

StringBuilder オブジェクトへのテキストの追加

クラスには StringBuilder 、オブジェクトの内容を展開するための次のメソッドが StringBuilder 含まれています。

  • メソッドは Append 、文字列、部分文字列、文字配列、文字配列の一部、1 つの文字を複数回繰り返す、またはプリミティブ データ型の文字列表現を オブジェクトに StringBuilder 追加します。

  • メソッドは AppendLine 、行終端記号または文字列を、行終端記号と共に オブジェクトに StringBuilder 追加します。

  • メソッドは AppendFormat複合書式指定文字列 を オブジェクトに StringBuilder 追加します。 結果文字列に含まれるオブジェクトの文字列表現には、現在のシステム カルチャまたは指定したカルチャの書式設定規則を反映できます。

  • メソッドは Insert 、文字列、部分文字列、文字列の複数の繰り返し、文字配列、文字配列の一部、またはプリミティブ データ型の文字列表現を オブジェクト内の指定した位置に StringBuilder 挿入します。 位置は、0 から始まるインデックスによって定義されます。

次の例では、 AppendAppendLineAppendFormat、および Insert の各メソッドを使用して、オブジェクトのテキストを StringBuilder 展開します。

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

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

StringBuilder オブジェクトからテキストを削除する

StringBuilderクラスには、現在StringBuilderのインスタンスのサイズを小さくできるメソッドが含まれています。 メソッドは Clear 、すべての文字を削除し、 プロパティを Length 0 に設定します。 メソッドは Remove 、特定のインデックス位置から始まる指定した数の文字を削除します。 さらに、オブジェクトのプロパティを現在のインスタンスの StringBuilder 長さより小さい値に設定 Length することで、オブジェクトの末尾から文字を削除できます。

次の例では、オブジェクトからテキストの一部を StringBuilder 削除し、その結果の容量、最大容量、および長さのプロパティ値を表示し、 メソッドを Clear 呼び出してオブジェクトからすべての文字を StringBuilder 削除します。

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

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

StringBuilder オブジェクト内のテキストの変更

メソッドは StringBuilder.Replace 、オブジェクト全体 StringBuilder または特定の文字範囲内の文字または文字列のすべての出現箇所を置き換えます。 次の例では、 メソッドを Replace 使用して、オブジェクト内のすべての感嘆符 (!) を StringBuilder 疑問符 (?) に置き換えます。

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?
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 オブジェクト内のテキストを検索する

クラスにはStringBuilder、 クラスによってString提供される 、String.IndexOf、および String.StartsWith メソッドのようなString.Containsメソッドは含まれていません。これにより、オブジェクトで特定の文字または部分文字列を検索できます。 部分文字列の存在または開始文字の位置を特定するには、文字列検索 String メソッドまたは正規表現メソッドを使用して値を検索する必要があります。 次の表に示すように、このような検索を実装する方法は 4 つあります。

手法 長所 短所
文字列値をオブジェクトに追加する前に StringBuilder 検索します。 部分文字列が存在するかどうかを判断するのに役立ちます。 部分文字列のインデックス位置が重要な場合は使用できません。
返されたStringオブジェクトを呼び出ToStringして検索します。 すべてのテキスト StringBuilder をオブジェクトに割り当ててから変更を開始する場合は、使いやすいです。 すべてのテキストがオブジェクトに追加される前に変更を加える必要がある場合は、 を繰り返し呼び出 ToString すのが StringBuilder 面倒です。

変更を加える場合は、 StringBuilder オブジェクトのテキストの末尾から作業を忘れずに行う必要があります。
プロパティを Chars[] 使用して、文字の範囲を順番に検索します。 個々の文字や小さな部分文字列に関心がある場合に便利です。 検索する文字数が多い場合や、検索ロジックが複雑な場合は面倒です。

メソッド呼び出しの繰り返しによって非常に大きくなったオブジェクトのパフォーマンスが非常に低くなります。
オブジェクトを StringBuilder オブジェクトに String 変換し、オブジェクトに対して変更を String 実行します。 変更の数が少ない場合に便利です。 変更の数が多い場合は、 StringBuilder クラスのパフォーマンス上の利点を否定します。

これらの手法を詳しく調べてみましょう。

  • 検索の目的が、特定の部分文字列が存在するかどうかを判断することです (つまり、部分文字列の位置に関心がない場合)、文字列をオブジェクトに格納する StringBuilder 前に検索できます。 次の例では、1 つの可能な実装を示します。 コンストラクターが StringBuilderFinder オブジェクトへの参照と文字列内で検索する部分文字列を StringBuilder 渡すクラスを定義します。 この場合、この例では、記録された温度が華氏か摂氏かを判断し、適切な入門テキストをオブジェクトの StringBuilder 先頭に追加します。 乱数ジェネレーターを使用して、摂氏または華氏のデータを含む配列を選択します。

    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
    
    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 Example
       Public Sub Main()
          Dim rnd As New Random()
          Dim tempF() As String = { "47.6F", "51.3F", "49.5F", "62.3F" }
          Dim tempC() As String = { "21.2C", "16.1C", "23.5C", "22.9C" }
          Dim temps()() As String = { tempF, tempC } 
    
          Dim sb As StringBuilder = New StringBuilder()
          Dim f As New StringBuilderFinder(sb, "F")
          Dim baseDate As New DateTime(2013, 5, 1) 
          Dim temperatures() As String = temps(rnd.Next(2))
          Dim isFahrenheit As Boolean = False
          For Each temperature In temperatures
             If isFahrenheit Then
                sb.AppendFormat("{0:d}: {1}{2}", baseDate, temperature, vbCrLf)
             Else
                isFahrenheit = f.SearchAndAppend(String.Format("{0:d}: {1}{2}", 
                                                 baseDate, temperature, vbCrLf))
             End If
             baseDate = baseDate.AddDays(1)
          Next            
          If isFahrenheit Then
             sb.Insert(0, "Average Daily Temperature in Degrees Fahrenheit")
             sb.Insert(47, vbCrLf + vbCrLf)
          Else
             sb.Insert(0, "Average Daily Temperature in Degrees Celsius")
             sb.Insert(44, vbCrLf + vbCrLf)
          End If   
          Console.WriteLine(sb.ToString())
       End Sub
    End Module
    
    Public Class StringBuilderFinder
       Private sb As StringBuilder
       Private text As String
       
       Public Sub New(sb As StringBuilder, textToFind As String)
          Me.sb = sb
          text = textToFind
       End Sub
       
       Public Function SearchAndAppend(stringToSearch As String) As Boolean
          sb.Append(stringToSearch)
          Return stringToSearch.Contains(text)
       End Function
    End Class
    ' The example displays output similar to the following:
    '    Average Daily Temperature in Degrees Celsius
    '    
    '    5/1/2013: 21.2C
    '    5/2/2013: 16.1C
    '    5/3/2013: 23.5C
    '    5/4/2013: 22.9C
    
  • オブジェクトを StringBuilder.ToString オブジェクトに変換するには、 StringBuilder メソッドを String 呼び出します。 や String.StartsWithなどのString.LastIndexOfメソッドを使用して文字列を検索することも、正規表現と クラスを使用してパターンをRegex検索することもできます。 と の両方 StringBuilderString オブジェクトは文字を格納するために UTF-16 エンコードを使用するため、文字、部分文字列、正規表現の一致のインデックス位置は両方のオブジェクトで同じです。 これにより、メソッドを使用 StringBuilder して、そのテキストがオブジェクト内で見つかるのと同じ位置に変更を String 加えます。

    注意

    この方法を採用する場合は、オブジェクトを StringBuilder 文字列に繰り返し変換する必要がないように、オブジェクトの末尾から先頭まで作業する StringBuilder 必要があります。

    このアプローチの例を次に示します。 これは、オブジェクトに英語のアルファベットの各文字の4回の出現を StringBuilder 格納します。 次に、テキストを オブジェクトに String 変換し、正規表現を使用して各 4 文字シーケンスの開始位置を識別します。 最後に、最初のシーケンスを除く各 4 文字シーケンスの前にアンダースコアを追加し、シーケンスの最初の文字を大文字に変換します。

    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
    
    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 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[] 文字範囲を順番に検索するには、 プロパティを StringBuilder 使用します。 検索する文字数が多い場合や、検索ロジックが特に複雑な場合、この方法は実用的でない場合があります。 非常に大きくチャンクされた StringBuilder オブジェクトに対する文字単位のインデックスベースのアクセスのパフォーマンスへの影響については、 プロパティのドキュメントを StringBuilder.Chars[] 参照してください。

    次の例は、前の例と同じ機能ですが、実装では異なります。 プロパティを Chars[] 使用して、文字値がいつ変更されたかを検出し、その位置にアンダースコアを挿入し、新しいシーケンスの最初の文字を大文字に変換します。

    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
    
    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 Example
       Public Sub Main()
          ' Create a StringBuilder object with 4 successive occurrences 
          ' of each character in the English alphabet. 
          Dim sb As New StringBuilder()
          For ctr As UShort = AscW("a") To Ascw("z")
             sb.Append(ChrW(ctr), 4)
          Next    
          ' Iterate the text to determine when a new character sequence occurs.
          Dim position As Integer = 0
          Dim current As Char = ChrW(0)
          Do
             If sb(position) <> current Then
                current = sb(position)
                sb(position) = Char.ToUpper(sb(position))
                If position > 0 Then sb.Insert(position, "_")
                position += 2
             Else
                position += 1
             End If      
          Loop While position <= sb.Length - 1
          ' Display the resulting string.
          Dim sbString As String = sb.ToString()
          Dim line As Integer = 0
          Do
             Dim nChars As Integer = If(line * 80 + 79 <= sbString.Length, 
                                        80, sbString.Length - line * 80)
             Console.WriteLine(sbString.Substring(line * 80, nChars))
             line += 1
          Loop While line * 80 < sbString.Length
       End Sub
    End Module
    ' The example displays the following output:
    '    Aaaa_Bbbb_Cccc_Dddd_Eeee_Ffff_Gggg_Hhhh_Iiii_Jjjj_Kkkk_Llll_Mmmm_Nnnn_Oooo_Pppp_
    '    Qqqq_Rrrr_Ssss_Tttt_Uuuu_Vvvv_Wwww_Xxxx_Yyyy_Zzzz
    
  • 変更されていないテキストをすべて オブジェクトに StringBuilder 格納し、 メソッドを StringBuilder.ToString 呼び出してオブジェクトを StringBuilder オブジェクトに String 変換し、オブジェクトに対して変更を String 実行します。 この方法は、いくつかの変更しかない場合に使用できます。そうしないと、変更できない文字列を操作するコストが、オブジェクトを使用するパフォーマンス上の利点を StringBuilder 否定する可能性があります。

    次の例は、前の 2 つの例と機能で同じですが、実装では異なります。 オブジェクトを StringBuilder 作成し、オブジェクトに String 変換した後、正規表現を使用して文字列に対して残りのすべての変更を実行します。 メソッドは Regex.Replace(String, String, MatchEvaluator) ラムダ式を使用して、一致するたびに置換を実行します。

    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
    
    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 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 オブジェクトを文字列に変換する

StringBuilder オブジェクトで表される文字列を String パラメーターを持つメソッドに渡すかそれをユーザー インターフェイスに表示するには、事前に StringBuilder オブジェクトを String オブジェクトに変換する必要があります。 この変換は、 メソッドを呼び出して実行します StringBuilder.ToString 。 図については、前の例を参照してください。この例では、 メソッドを ToString 呼び出してオブジェクトを文字列に変換 StringBuilder し、正規表現メソッドに渡すことができます。

注意 (呼び出し元)

.NET Core および .NET Framework 4.0 以降のバージョンでは、コンストラクターを呼び出StringBuilder(Int32, Int32)してオブジェクトをインスタンス化StringBuilderすると、インスタンスの長さと容量のStringBuilder両方が、そのMaxCapacityプロパティの値を超えて拡張される可能性があります。 これは、特に メソッドと AppendFormat(String, Object) メソッドを呼び出Append(String)して小さな文字列を追加するときに発生する可能性があります。

コンストラクター

StringBuilder()

StringBuilder クラスの新しいインスタンスを初期化します。

StringBuilder(Int32)

指定した容量を使用して、StringBuilder クラスの新しいインスタンスを初期化します。

StringBuilder(Int32, Int32)

指定した容量で始まり、指定した最大容量まで大きくなる StringBuilder クラスの新しいインスタンスを初期化します。

StringBuilder(String)

指定した文字列を使用して、StringBuilder クラスの新しいインスタンスを初期化します。

StringBuilder(String, Int32)

指定した文字列および容量を使用して、StringBuilder クラスの新しいインスタンスを初期化します。

StringBuilder(String, Int32, Int32, Int32)

指定した部分文字列および容量から StringBuilder クラスの新しいインスタンスを初期化します。

プロパティ

Capacity

現在のインスタンスによって割り当てられたメモリに格納できる最大文字数を取得または設定します。

Chars[Int32]

このインスタンス内の指定した文字位置の文字を取得または設定します。

Length

現在の StringBuilder オブジェクトの長さを取得または設定します。

MaxCapacity

このインスタンスの最大容量を取得します。

メソッド

Append(Boolean)

指定した Boolean 値の文字列形式をこのインスタンスに追加します。

Append(Byte)

指定した 8 ビット符号なし整数の文字列形式をこのインスタンスに追加します。

Append(Char)

指定した Char オブジェクトの文字列形式をこのインスタンスに追加します。

Append(Char*, Int32)

指定したアドレスで始まる Unicode 文字の配列をこのインスタンスに追加します。

Append(Char, Int32)

Unicode 文字の文字列形式の、指定した数のコピーをこのインスタンスに追加します。

Append(Char[])

指定した配列内の Unicode 文字の文字列形式をこのインスタンスに追加します。

Append(Char[], Int32, Int32)

Unicode 文字の指定した部分配列の文字列形式をこのインスタンスに追加します。

Append(Decimal)

指定した 10 進数の文字列形式をこのインスタンスに追加します。

Append(Double)

指定した倍精度浮動小数点数の文字列形式をこのインスタンスに追加します。

Append(IFormatProvider, StringBuilder+AppendInterpolatedStringHandler)

指定した書式を使用して、指定した補間文字列をこのインスタンスに追加します。

Append(Int16)

指定した 16 ビット符号付き整数の文字列形式をこのインスタンスに追加します。

Append(Int32)

指定した 32 ビット符号付き整数の文字列形式をこのインスタンスに追加します。

Append(Int64)

指定した 64 ビット符号付き整数の文字列形式をこのインスタンスに追加します。

Append(Object)

指定したオブジェクトの文字列形式をこのインスタンスに追加します。

Append(ReadOnlyMemory<Char>)

指定された読み取り専用文字メモリ領域の文字列形式をこのインスタンスに追加します。

Append(ReadOnlySpan<Char>)

指定された読み取り専用文字スパンの文字列形式をこのインスタンスに追加します。

Append(SByte)

指定した 8 ビット符号付き整数の文字列形式をこのインスタンスに追加します。

Append(Single)

指定した単精度浮動小数点数の文字列形式をこのインスタンスに追加します。

Append(String)

指定した文字列のコピーをこのインスタンスに追加します。

Append(String, Int32, Int32)

指定した部分文字列のコピーをこのインスタンスに追加します。

Append(StringBuilder)

指定された文字列ビルダーの文字列形式をこのインスタンスに追加します。

Append(StringBuilder, Int32, Int32)

指定された文字列ビルダー内の部分文字列のコピーをこのインスタンスに追加します。

Append(StringBuilder+AppendInterpolatedStringHandler)

指定した補間文字列をこのインスタンスに追加します。

Append(UInt16)

指定した 16 ビット符号なし整数の文字列形式をこのインスタンスに追加します。

Append(UInt32)

指定された 32 ビット符号なし整数の文字列表記をこのインスタンスに追加します。

Append(UInt64)

指定した 64 ビット符号なし整数の文字列形式をこのインスタンスに追加します。

AppendFormat(IFormatProvider, CompositeFormat, Object[])

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式項目は、指定された書式プロバイダーを使用して、引数の文字列表現に置き換えられます。

AppendFormat(IFormatProvider, CompositeFormat, ReadOnlySpan<Object>)

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式項目は、指定された書式プロバイダーを使用して、引数の文字列表現に置き換えられます。

AppendFormat(IFormatProvider, String, Object)

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式指定項目は、指定された書式プロバイダーを使用して単一の引数の文字列形式に置換されます。

AppendFormat(IFormatProvider, String, Object, Object)

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式項目は、指定された書式プロバイダーを使用して 2 つの引数のいずれかの文字列形式に置換されます。

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

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式項目は、指定された書式プロバイダーを使用して 3 つの引数のいずれかの文字列形式に置換されます。各書式項目は、指定された書式プロバイダーを使用して 3 つの引数のいずれかの文字列形式に置換されます。

AppendFormat(IFormatProvider, String, Object[])

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式項目は、指定された書式プロバイダーを使用した、パラメーター配列内の対応する引数の文字列形式に置換されます。

AppendFormat(String, Object)

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式項目は、単一の引数の文字列表記に置換されます。

AppendFormat(String, Object, Object)

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式項目は、2 つの引数のどちらかの文字列形式に置換されます。

AppendFormat(String, Object, Object, Object)

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式項目は、3 つの引数のいずれかの文字列形式に置換されます。

AppendFormat(String, Object[])

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式項目は、パラメーター配列内の対応する引数の文字列形式に置換されます。

AppendFormat<TArg0,TArg1,TArg2>(IFormatProvider, CompositeFormat, TArg0, TArg1, TArg2)

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式項目は、指定された書式プロバイダーを使用して、引数の文字列表現に置き換えられます。

AppendFormat<TArg0,TArg1>(IFormatProvider, CompositeFormat, TArg0, TArg1)

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式項目は、指定された書式プロバイダーを使用して、引数の文字列表現に置き換えられます。

AppendFormat<TArg0>(IFormatProvider, CompositeFormat, TArg0)

0 個以上の書式項目を含んでいる複合書式指定文字列を処理することで返される文字列を、このインスタンスに追加します。 各書式項目は、指定された書式プロバイダーを使用して、引数の文字列表現に置き換えられます。

AppendJoin(Char, Object[])

指定したオブジェクト配列内の要素の文字列表現を連結します。各メンバー間には、指定した区切り文字が使用され、その結果は文字列ビルダーの現在のインスタンスに追加されます。

AppendJoin(Char, String[])

指定した配列の文字列を連結します。各文字列間には、指定した区切り文字が使用され、その結果は文字列ビルダーの現在のインスタンスに追加されます。

AppendJoin(String, Object[])

指定したオブジェクト配列内の要素の文字列表現を連結します。各メンバー間には、指定した区切り記号が使用され、その結果は文字列ビルダーの現在のインスタンスに追加されます。

AppendJoin(String, String[])

指定した配列の文字列を連結します。各文字列間には、指定した区切り記号が使用され、その結果は文字列ビルダーの現在のインスタンスに追加されます。

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

コレクションのメンバーを連結および追加します。各メンバー間には、指定した区切り文字が使用されます。

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

コレクションのメンバーを連結および追加します。各メンバー間には、指定した区切り記号が使用されます。

AppendLine()

既定の行終端記号を現在の StringBuilder オブジェクトの末尾に追加します。

AppendLine(IFormatProvider, StringBuilder+AppendInterpolatedStringHandler)

現在の StringBuilder オブジェクトの末尾に、指定した形式を使用して、指定した挿入文字列を追加します。その後に既定の行ターミネータが続きます。

AppendLine(String)

指定した文字列のコピーと既定の行終端記号を、現在の StringBuilder オブジェクトの末尾に追加します。

AppendLine(StringBuilder+AppendInterpolatedStringHandler)

現在の StringBuilder オブジェクトの末尾に、指定した補間文字列の後に既定の行終端記号を追加します。

Clear()

現在の StringBuilder インスタンスからすべての文字を削除します。

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

このインスタンスの指定したセグメントにある文字を、目的の Char 配列の指定したセグメントにコピーします。

CopyTo(Int32, Span<Char>, Int32)

文字をこのインスタンスの指定したセグメントから目的の Char のスパンにコピーします。

EnsureCapacity(Int32)

このインスタンスの StringBuilder の容量が、指定した値以上になるようにします。

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
Equals(ReadOnlySpan<Char>)

このインスタンスの文字が、指定された読み取り専用の文字範囲内の文字と同じであるかどうかを示す値を返します。

Equals(StringBuilder)

このインスタンスが指定されたオブジェクトに等しいかどうかを示す値を返します。

GetChunks()

この StringBuilder インスタンスから作成された ReadOnlyMemory<Char> で表される文字のチャンクを反復処理する目的で利用できるオブジェクトを返します。

GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
Insert(Int32, Boolean)

Boolean 値の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, Byte)

指定した 8 ビット符号なし整数の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, Char)

指定した Unicode 文字の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, Char[])

指定した Unicode 文字の配列の文字列形式をこのインスタンスの指定した文字位置に挿入します。

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

Unicode 文字の指定した部分配列の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, Decimal)

10 進数の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, Double)

倍精度浮動小数点数の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, Int16)

指定した 16 ビット符号付き整数の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, Int32)

指定した 32 ビット符号付き整数の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, Int64)

64 ビット符号付き整数の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, Object)

オブジェクトの文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, ReadOnlySpan<Char>)

文字のシーケンスをこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, SByte)

指定した 8 ビット符号付き整数の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, Single)

単精度浮動小数点数の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, String)

文字列をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, String, Int32)

指定した文字列の 1 つ以上のコピーをこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, UInt16)

16 ビット符号なし整数の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, UInt32)

32 ビット符号なし整数の文字列形式をこのインスタンスの指定した文字位置に挿入します。

Insert(Int32, UInt64)

64 ビット符号なし整数の文字列形式をこのインスタンスの指定した文字位置に挿入します。

MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
Remove(Int32, Int32)

このインスタンスから、指定した範囲の文字を削除します。

Replace(Char, Char)

このインスタンスに出現する指定文字をすべて、別に指定した文字に置換します。

Replace(Char, Char, Int32, Int32)

このインスタンスの部分文字列に出現するすべての指定した文字を、別の指定した文字に置換します。

Replace(String, String)

このインスタンスに出現するすべての指定した文字列を、別の指定した文字列に置換します。

Replace(String, String, Int32, Int32)

このインスタンスの部分文字列に出現するすべての指定した文字列を、別の指定した文字列に置換します。

ToString()

このインスタンスの値を String に変換します。

ToString(Int32, Int32)

このインスタンスの部分文字列の値を String に変換します。

明示的なインターフェイスの実装

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

SerializationInfo オブジェクトに、現在の StringBuilder オブジェクトの逆シリアル化に必要なデータを入力します。

適用対象

こちらもご覧ください