.NET の StringBuilder クラスを使用する

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

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

StringBuilder クラスは、System.Text 名前空間にあります。 完全修飾型名をコードに指定しなくてもすむように、System.Text 名前空間をインポートすることができます。

using namespace System;
using namespace System::Text;
using System;
using System.Text;
Imports System.Text

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

以下の例に示すように、オーバーロードされたコンストラクター メソッドの 1 つで変数を初期化することにより、StringBuilder クラスの新しいインスタンスを作成することができます。

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

容量と長さの設定

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

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

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

myStringBuilder->Capacity = 25;
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 = gcnew 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 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.

AppendFormat

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

int MyInt = 25;
StringBuilder^ myStringBuilder = gcnew StringBuilder("Your total is ");
myStringBuilder->AppendFormat("{0:C} ", MyInt);
Console::WriteLine(myStringBuilder);
// The example displays the following output:
//       Your total is $25.00
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 = gcnew StringBuilder("Hello World!");
myStringBuilder->Insert(6,"Beautiful ");
Console::WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello Beautiful World!
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 = gcnew StringBuilder("Hello World!");
myStringBuilder->Remove(5,7);
Console::WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello
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

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

StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!");
myStringBuilder->Replace('!', '?');
Console::WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello World?
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

関連項目