複数の文字列を連結する方法 (C# ガイド)

連結とは、ある文字列を別の文字列の末尾に追加するプロセスです。 文字列を連結するには、+ 演算子を使用します。 文字列リテラルと文字列定数の場合、連結はコンパイル時に行われ、実行時には行われません。 文字列変数の連結は実行時にのみ行われます。

注意

この記事の C# 例は、Try.NET インライン コード ランナーとプレイグラウンドで実行されます。 [実行] ボタンを選択すると、対話型ウィンドウで例が実行されます。 コードを実行したら、コードを変更し、 [実行] をもう一度選択して変更後のコードを実行できます。 変更後のコードが対話型ウィンドウで実行されるか、コンパイルできなかった場合、対話型ウィンドウにすべての C# コンパイラ エラー メッセージが表示されます。

文字列リテラル

次の例では、ソース コードを読みやすくするために、長い文字列リテラルを短い文字列に分割しています。 このコードによって、短い文字列が連結され、長い文字列リテラルが作成されます。 各部分はコンパイル時に連結され、単一の文字列が作成されます。 関係する文字列の数に関係なく、実行時にパフォーマンス コストは発生しません。

// Concatenation of literals is performed at compile time, not run time.
string text = "Historically, the world of data and the world of objects " +
"have not been well integrated. Programmers work in C# or Visual Basic " +
"and also in SQL or XQuery. On the one side are concepts such as classes, " +
"objects, fields, inheritance, and .NET Framework APIs. On the other side " +
"are tables, columns, rows, nodes, and separate languages for dealing with " +
"them. Data types often require translation between the two worlds; there are " +
"different standard functions. Because the object world has no notion of query, a " +
"query can only be represented as a string without compile-time type checking or " +
"IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to " +
"objects in memory is often tedious and error-prone.";

System.Console.WriteLine(text);

+ 演算子と += 演算子

文字列変数を連結する場合は、+ または += 演算子、文字列補間または String.FormatString.ConcatString.JoinStringBuilder.Append メソッドを使用できます。 + 演算子は使い方が簡単で、直感的なコードにすることができます。 1 つのステートメントで複数の + 演算子を使用している場合でも、文字列の内容がコピーされるのは 1 回のみです。 次のコードは、+ および += 演算子を使用して文字列を連結する例を示しています。

string userName = "<Type your name here>";
string dateString = DateTime.Today.ToShortDateString();

// Use the + and += operators for one-time concatenations.
string str = "Hello " + userName + ". Today is " + dateString + ".";
System.Console.WriteLine(str);

str += " How are you today?";
System.Console.WriteLine(str);

文字列補間

式によっては、次のコードに示すように、文字列補間を使用して文字列を連結する方が簡単な場合があります。

string userName = "<Type your name here>";
string date = DateTime.Today.ToShortDateString();

// Use string interpolation to concatenate strings.
string str = $"Hello {userName}. Today is {date}.";
System.Console.WriteLine(str);

str = $"{str} How are you today?";
System.Console.WriteLine(str);

注意

文字列連結操作において、C# コンパイラでは null 文字列は空の文字列と同様に扱われます。

C# 10 以降では、プレースホルダーに使用されるすべての式が定数文字列である場合も、文字列補間を使用して定数文字列を初期化できます。

String.Format

文字列を連結する別のメソッドとして、String.Format があります。 このメソッドは、少数のコンポーネント文字列から文字列を作成する場合に有効です。

StringBuilder

他にも、結合するソース文字列の数がわからないループ内の文字列を結合する場合、ソース文字列の実際の数は大きくなる可能性があります。 StringBuilder クラスは、このようなシナリオのために設計されています。 次のコードでは、StringBuilder クラスの Append メソッドを使用して文字列を連結しています。

// Use StringBuilder for concatenation in tight loops.
var sb = new System.Text.StringBuilder();
for (int i = 0; i < 20; i++)
{
    sb.AppendLine(i.ToString());
}
System.Console.WriteLine(sb.ToString());

文字列の連結または StringBuilder クラスを選択する理由に関するページで詳細をご確認ください。

String.Concat または String.Join

コレクションからの文字列を結合する別のオプションとして、String.Concat メソッドを使用する方法があります。 区切り記号でソース文字列を区切る必要がある場合は、String.Join メソッドを使用します。 次のコードでは、両方のメソッドを使用して単語の配列を結合します。

string[] words = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." };

var unreadablePhrase = string.Concat(words);
System.Console.WriteLine(unreadablePhrase);

var readablePhrase = string.Join(" ", words);
System.Console.WriteLine(readablePhrase);

LINQ と Enumerable.Aggregate

最後に、LINQ および Enumerable.Aggregate メソッドを使用して、コレクションからの文字列を結合できます。 このメソッドは、ラムダ式を使用してソース文字列を結合します。 ラムダ式は、各文字列を既存の蓄積に追加する処理を行います。 次の例では、配列内の各単語の間にスペースを追加し、単語の配列を結合します。

string[] words = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." };

var phrase = words.Aggregate((partialPhrase, word) =>$"{partialPhrase} {word}");
System.Console.WriteLine(phrase);

このオプションを使用すると、コレクションを連結する他のメソッドよりも多くの割り当てが発生する可能性があります。これは、反復ごとに中間文字列が作成されるためです。 パフォーマンスの最適化が重要な場合、コレクションの連結に、Enumerable.Aggregate ではなく、StringBuilderクラスか、String.Concat または String.Join メソッドを検討してください。

関連項目