.NET では、単純な割り当てを使用して文字列を作成できます。また、クラス コンストラクターをオーバーロードして、さまざまなパラメーターを使用した文字列の作成をサポートします。 .NET には、複数の文字列、文字列の配列、またはオブジェクトを組み合わせて新しい文字列オブジェクトを作成する、 System.String クラスのいくつかのメソッドも用意されています。
代入を使用して文字列を作成する
新しい String オブジェクトを作成する最も簡単な方法は、文字列リテラルを String オブジェクトに割り当てることです。
クラス コンストラクターを使用して文字列を作成する
String クラス コンストラクターのオーバーロードを使用して、文字配列から文字列を作成できます。 指定した回数だけ特定の文字を複製することで、新しい文字列を作成することもできます。 String(ReadOnlySpan<Char>)コンストラクターオーバーロードは、ReadOnlySpan<T>またはスタック割り当てSpan<T>の文字を受け取り、既知のサイズの小さな文字列をビルドするときにマネージド ヒープに中間文字配列を割り当てることを回避しますが、結果の文字列インスタンスはマネージド ヒープに引き続き割り当てられます。
文字列を返すメソッド
次の表に、新しい文字列オブジェクトを返す便利なメソッドをいくつか示します。
| メソッド名 | 使用 |
|---|---|
| String.Format | 一連の入力オブジェクトから書式設定された文字列を作成します。 |
| String.Concat | 2 つ以上の文字列から文字列をビルドします。 |
| String.Join | 文字列の配列を組み合わせて新しい文字列を構築します。 |
| String.Insert | 既存の文字列の指定したインデックスに文字列を挿入して、新しい文字列を作成します。 |
| String.CopyTo | 文字列内の指定した文字を、文字の配列内の指定した位置にコピーします。 |
| String.Create | 指定した長さの新しい文字列を作成し、書き込み可能な Span<T> と呼び出し元が指定した状態オブジェクトを受け取るコールバックを介して文字を入力します。 |
String.Format
String.Formatメソッドを使用すると、書式設定された文字列を作成し、複数のオブジェクトを表す文字列を連結できます。 このメソッドは、渡されたオブジェクトを文字列に自動的に変換します。 たとえば、アプリケーションで Int32 値と DateTime 値をユーザーに表示する必要がある場合は、 Format メソッドを使用して、これらの値を表す文字列を簡単に作成できます。 このメソッドで使用される書式設定規則の詳細については、 複合書式のセクションを参照してください。
次の例では、 Format メソッドを使用して、整数変数を使用する文字列を作成します。
int numberOfFleas = 12;
string miscInfo = String.Format("Your dog has {0} fleas. " +
"It is time to get a flea collar. " +
"The current universal date is: {1:u}.",
numberOfFleas, DateTime.Now);
Console.WriteLine(miscInfo);
// The example displays the following output:
// Your dog has 12 fleas. It is time to get a flea collar.
// The current universal date is: 2008-03-28 13:31:40Z.
Dim numberOfFleas As Integer = 12
Dim miscInfo As String = String.Format("Your dog has {0} fleas. " & _
"It is time to get a flea collar. " & _
"The current universal date is: {1:u}.", _
numberOfFleas, Date.Now)
Console.WriteLine(miscInfo)
' The example displays the following output:
' Your dog has 12 fleas. It is time to get a flea collar.
' The current universal date is: 2008-03-28 13:31:40Z.
この例では、 DateTime.Now 現在のスレッドに関連付けられているカルチャで指定された方法で現在の日付と時刻を表示します。
String.Concat
String.Concat メソッドを使用すると、2 つ以上の既存のオブジェクトから新しい文字列オブジェクトを簡単に作成できます。 これは、文字列を連結する言語に依存しない方法を提供します。 このメソッドは、 System.Objectから派生するすべてのクラスを受け入れます。 次の例では、既存の 2 つの文字列オブジェクトと区切り文字から文字列を作成します。
string helloString1 = "Hello";
string helloString2 = "World!";
Console.WriteLine(String.Concat(helloString1, ' ', helloString2));
// The example displays the following output:
// Hello World!
Dim helloString1 As String = "Hello"
Dim helloString2 As String = "World!"
Console.WriteLine(String.Concat(helloString1, " "c, helloString2))
' The example displays the following output:
' Hello World!
String.Join
String.Join メソッドは、文字列の配列と区切り文字列から新しい文字列を作成します。 このメソッドは、複数の文字列を連結して、リストをコンマで区切る場合に便利です。
次の例では、スペースを使用して文字列配列をバインドします。
string[] words = {"Hello", "and", "welcome", "to", "my" , "world!"};
Console.WriteLine(String.Join(" ", words));
// The example displays the following output:
// Hello and welcome to my world!
Dim words() As String = {"Hello", "and", "welcome", "to", "my", "world!"}
Console.WriteLine(String.Join(" ", words))
' The example displays the following output:
' Hello and welcome to my world!
String.Insert
String.Insert メソッドは、別の文字列内の指定した位置に文字列を挿入して、新しい文字列を作成します。 このメソッドでは、0 から始まるインデックスが使用されます。 次の例では、 MyString の 5 番目のインデックス位置に文字列を挿入し、この値を使用して新しい文字列を作成します。
string sentence = "Once a time.";
Console.WriteLine(sentence.Insert(4, " upon"));
// The example displays the following output:
// Once upon a time.
Dim sentence As String = "Once a time."
Console.WriteLine(sentence.Insert(4, " upon"))
' The example displays the following output:
' Once upon a time.
String.CopyTo
String.CopyTo メソッドは、文字列の一部を文字の配列にコピーします。 文字列の先頭インデックスとコピーする文字数の両方を指定できます。 このメソッドは、コピー元のインデックス、文字の配列、コピー先のインデックス、およびコピーする文字数を受け取ります。 すべてのインデックスは 0 から始まります。
次の例では、 CopyTo メソッドを使用して、文字列オブジェクトから文字配列の最初のインデックス位置に単語 "Hello" の文字をコピーします。
string greeting = "Hello World!";
char[] charArray = {'W','h','e','r','e'};
Console.WriteLine($"The original character array: {new string(charArray)}");
greeting.CopyTo(0, charArray,0 ,5);
Console.WriteLine($"The new character array: {new string(charArray)}");
// The example displays the following output:
// The original character array: Where
// The new character array: Hello
Dim greeting As String = "Hello World!"
Dim charArray() As Char = {"W"c, "h"c, "e"c, "r"c, "e"c}
Console.WriteLine("The original character array: {0}", New String(charArray))
greeting.CopyTo(0, charArray, 0, 5)
Console.WriteLine("The new character array: {0}", New String(charArray))
' The example displays the following output:
' The original character array: Where
' The new character array: Hello
String.Create
String.Create メソッドを使用すると、コールバックを使用してプログラムで新しい文字列の文字を入力できます。 コールバックは、文字の書き込み可能な Span<T> と呼び出し元が指定した状態オブジェクトを受け取るので、中間文字バッファーを割り当てずに文字列のコンテンツを構築できます。 コールバック自体は、ローカル変数をキャプチャしたり、他の割り当て負荷の高い API を呼び出したりする場合など、引き続き割り当てることができます。
次の例では、 String.Create を使用して、連続するアルファベット文字から 5 文字の文字列を作成します。
string result = string.Create(5, 'a', (span, firstChar) =>
{
for (int i = 0; i < span.Length; i++)
{
span[i] = (char)(firstChar + i);
}
});
Console.WriteLine(result); // abcde
Module Program
Sub Main()
Dim result As String = String.Create(5, "a"c, Sub(span, firstChar)
For i As Integer = 0 To span.Length - 1
span(i) = ChrW(AscW(firstChar) + i)
Next
End Sub)
Console.WriteLine(result) ' abcde
End Sub
End Module
String.Create は、最終的な文字列の長さを事前に把握しており、中間文字バッファーの割り当てを避けたい、パフォーマンスに依存するシナリオ向けに設計されています。 ランタイムは新しい文字列を割り当て、そのバッキング バッファーを Span<char>としてコールバックに直接渡し、コールバックが戻ると変更できない文字列を返します。 コールバックの完了後、データのコピーは行われません。
String.Create 対。 new String(Span<char>)
文字列を効率的に構築するためのもう 1 つのオプションは、 stackallocを使用して文字バッファーを割り当て、それを埋めて、 String(ReadOnlySpan<char>) コンストラクターに渡すことです。
static string CreateStringFromSpan()
{
Span<char> span = stackalloc char[5];
for (int i = 0; i < 5; i++)
{
span[i] = (char)('a' + i);
}
return new string(span);
}
Console.WriteLine(CreateStringFromSpan()); // abcde
どちらの方法でも、最後の文字列が 1 回だけ割り当てられます。 主な違いは次のとおりです。
-
stackalloc+new string(span)は、作業バッファーをスタックに配置します。 小さな固定サイズのバッファーでは最速ですが、スタックは有限のリソースです。大きな割り当てや深いネストを伴う割り当ては を引き起こす可能性があります。 この例では、C# stackallocパターンを示します。Visual Basic ではstackallocはサポートされていませんが、String(ReadOnlySpan<char>)がある場合でも、ReadOnlySpan<char>コンストラクターを呼び出すことができます。 -
String.Createは、文字列オブジェクト自体の一部としてヒープに作業バッファーを割り当てます。そのため、スタックの負荷はありません。 また、ランタイムがボックス化なしでコールバックに渡す型指定された状態パラメーターも受け取り、状態が参照型またはキャプチャされていない構造体である場合にボックス化の割り当てを回避します。 一般に、既知の有界サイズの小さな文字列 (通常は数百文字未満) にはstackalloc+new String(span)を使用します。String.Createサイズが大きくなる可能性がある場合、スタックの負荷を回避する場合、または状態をボックス化せずにコールバックに渡す場合に使用します。
こちらも参照ください
.NET