次の方法で共有


.NET での StringBuilder クラスの使用

String オブジェクトは変更できません。 System.String クラスのいずれかのメソッドを使用するたびに、メモリ内に新しい文字列オブジェクトを作成します。これには、その新しいオブジェクトに新しい領域を割り当てる必要があります。 文字列に対して繰り返し変更を実行する必要がある場合、新しい String オブジェクトの作成に関連するオーバーヘッドが高くなります。 System.Text.StringBuilder クラスは、新しいオブジェクトを作成せずに文字列を変更する場合に使用できます。 たとえば、 StringBuilder クラスを使用すると、ループ内で多数の文字列を連結するときにパフォーマンスを向上させることができます。

System.Text 名前空間のインポート

StringBuilder クラスは、System.Text名前空間にあります。 コードに完全修飾型名を指定する必要を回避するには、 System.Text 名前空間をインポートします。

using System;
using System.Text;
Imports System.Text

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

次の例に示すように、オーバーロードされたコンストラクター メソッドのいずれかを使用して変数を初期化することで、 StringBuilder クラスの新しいインスタンスを作成できます。

StringBuilder myStringBuilder = new StringBuilder("Hello World!");
Dim myStringBuilder As New StringBuilder("Hello World!")

容量と長さの設定

StringBuilderは、カプセル化する文字列内の文字数を拡張できる動的オブジェクトですが、保持できる最大文字数の値を指定できます。 この値はオブジェクトの容量と呼ばれ、現在の StringBuilder が保持する文字列の長さと混同しないでください。 たとえば、長さが 5 の文字列 "Hello" を使用して、 StringBuilder クラスの新しいインスタンスを作成し、オブジェクトの最大容量が 25 であることを指定できます。 StringBuilderを変更しても、容量に達するまで、それ自体のサイズは再割り当てされません。 これが発生すると、新しい領域が自動的に割り当てられ、容量が 2 倍になります。 オーバーロードされたコンストラクターのいずれかを使用して、 StringBuilder クラスの容量を指定できます。 次の例では、 myStringBuilder オブジェクトを最大 25 個のスペースに拡張できることを指定します。

StringBuilder myStringBuilder = new StringBuilder("Hello World!", 25);
Dim myStringBuilder As New StringBuilder("Hello World!", 25)

さらに、読み取り/書き込み Capacity プロパティを使用して、オブジェクトの最大長を設定できます。 次の例では、 Capacity プロパティを使用して、オブジェクトの最大長を定義します。

myStringBuilder.Capacity = 25;
myStringBuilder.Capacity = 25

EnsureCapacity メソッドを使用して、現在の StringBuilder の容量を確認できます。 容量が渡された値より大きい場合、変更は行われません。ただし、容量が渡された値より小さい場合、現在の容量は渡された値と一致するように変更されます。

Length プロパティは、表示または設定することもできます。 Length プロパティを Capacity プロパティより大きい値に設定すると、Capacity プロパティは Length プロパティと同じ値に自動的に変更されます。 Length プロパティを現在の StringBuilder 内の文字列の長さより小さい値に設定すると、文字列が短縮されます。

StringBuilder 文字列の変更

次の表に、 StringBuilder の内容を変更するために使用できるメソッドを示します。

メソッド名 使用
StringBuilder.Append 現在の StringBuilder の末尾に情報を追加します。
StringBuilder.AppendFormat 文字列で渡された書式指定子を書式設定されたテキストに置き換えます。
StringBuilder.Insert 現在の StringBuilder の指定したインデックスに文字列またはオブジェクトを挿入します。
StringBuilder.Remove 現在の StringBuilder から指定した文字数を削除します。
StringBuilder.Replace 現在の StringBuilder 内の指定した文字または文字列のすべての出現箇所を、別の指定した文字または文字列に置き換えます。

追加

Append メソッドを使用すると、現在の StringBuilder で表される文字列の末尾に、オブジェクトのテキストまたは文字列表現を追加できます。 次の例では、 StringBuilder を "Hello World" に初期化し、オブジェクトの末尾にいくつかのテキストを追加します。 領域は、必要に応じて自動的に割り当てられます。

StringBuilder myStringBuilder = new StringBuilder("Hello World!");
myStringBuilder.Append(" What a beautiful day.");
Console.WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello World! What a beautiful day.
Dim myStringBuilder As New StringBuilder("Hello World!")
myStringBuilder.Append(" What a beautiful day.")
Console.WriteLine(myStringBuilder)
' The example displays the following output:
'       Hello World! What a beautiful day.

アペンドフォーマット

StringBuilder.AppendFormat メソッドは、StringBuilder オブジェクトの末尾にテキストを追加します。 これは、書式設定するオブジェクトの実装を呼び出すことによってIFormattableをサポートします。 そのため、数値、日付と時刻、および列挙値の標準書式指定文字列、数値と日付と時刻の値のカスタム書式指定文字列、およびカスタム型に定義された書式指定文字列を受け取ります。 (書式設定の詳細については、「型の 書式設定」を参照してください。このメソッドを使用すると、変数の形式をカスタマイズし、それらの値を StringBuilderに追加できます。 次の例では、 AppendFormat メソッドを使用して、通貨値として書式設定された整数値を StringBuilder オブジェクトの末尾に配置します。

int MyInt = 25;
StringBuilder myStringBuilder = new StringBuilder("Your total is ");
myStringBuilder.AppendFormat("{0:C} ", MyInt);
Console.WriteLine(myStringBuilder);
// The example displays the following output:
//       Your total is $25.00
Dim MyInt As Integer = 25
Dim myStringBuilder As New StringBuilder("Your total is ")
myStringBuilder.AppendFormat("{0:C} ", MyInt)
Console.WriteLine(myStringBuilder)
' The example displays the following output:
'     Your total is $25.00  

[挿入]

Insert メソッドは、現在のStringBuilder オブジェクト内の指定した位置に文字列またはオブジェクトを追加します。 次の例では、このメソッドを使用して、 StringBuilder オブジェクトの 6 番目の位置に単語を挿入します。

StringBuilder myStringBuilder = new StringBuilder("Hello World!");
myStringBuilder.Insert(6,"Beautiful ");
Console.WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello Beautiful World!
Dim myStringBuilder As New StringBuilder("Hello World!")
myStringBuilder.Insert(6, "Beautiful ")
Console.WriteLine(myStringBuilder)
' The example displays the following output:
'      Hello Beautiful World!

削除する

Remove メソッドを使用すると、現在の StringBuilder オブジェクトから指定した数の文字を、指定した 0 から始まるインデックスから削除できます。 次の例では、 Remove メソッドを使用して、 StringBuilder オブジェクトを短縮します。

StringBuilder myStringBuilder = new StringBuilder("Hello World!");
myStringBuilder.Remove(5,7);
Console.WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello
Dim myStringBuilder As New StringBuilder("Hello World!")
myStringBuilder.Remove(5, 7)
Console.WriteLine(myStringBuilder)
' The example displays the following output:
'       Hello

取り替える

Replace メソッドを使用すると、StringBuilder オブジェクト内の文字を別の指定した文字に置き換えることができます。 次の例では 、Replace メソッドを使用して、感嘆符文字 (!) のすべてのインスタンスの StringBuilder オブジェクトを検索し、疑問符文字 (?) に置き換えます。

StringBuilder myStringBuilder = new StringBuilder("Hello World!");
myStringBuilder.Replace('!', '?');
Console.WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello World?
Dim myStringBuilder As New StringBuilder("Hello World!")
myStringBuilder.Replace("!"c, "?"c)
Console.WriteLine(myStringBuilder)
' The example displays the following output:
'       Hello World?

StringBuilder オブジェクトを文字列に変換する

StringBuilder オブジェクトで表される文字列を String パラメーターを持つメソッドに渡したり、ユーザー インターフェイスに表示したりする前に、StringBuilder オブジェクトを String オブジェクトに変換する必要があります。 この変換を行うには、 StringBuilder.ToString メソッドを呼び出します。 次の例では、複数の StringBuilder メソッドを呼び出し、 StringBuilder.ToString() メソッドを呼び出して文字列を表示します。

using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      StringBuilder sb = new StringBuilder();
      bool flag = true;
      string[] spellings = { "recieve", "receeve", "receive" };
      sb.AppendFormat("Which of the following spellings is {0}:", flag);
      sb.AppendLine();
      for (int ctr = 0; ctr <= spellings.GetUpperBound(0); ctr++) {
         sb.AppendFormat("   {0}. {1}", ctr, spellings[ctr]);
         sb.AppendLine();
      }
      sb.AppendLine();
      Console.WriteLine(sb.ToString());
   }
}
// The example displays the following output:
//       Which of the following spellings is True:
//          0. recieve
//          1. receeve
//          2. receive
Imports System.Text

Module Example
    Public Sub Main()
        Dim sb As New StringBuilder()
        Dim flag As Boolean = True
        Dim spellings() As String = {"recieve", "receeve", "receive"}
        sb.AppendFormat("Which of the following spellings is {0}:", flag)
        sb.AppendLine()
        For ctr As Integer = 0 To spellings.GetUpperBound(0)
            sb.AppendFormat("   {0}. {1}", ctr, spellings(ctr))
            sb.AppendLine()
        Next
        sb.AppendLine()
        Console.WriteLine(sb.ToString())
    End Sub
End Module
' The example displays the following output:
'       Which of the following spellings is True:
'          0. recieve
'          1. receeve
'          2. receive

こちらも参照ください