変数からテキストを追加した複数行の文字列 質問する

変数からテキストを追加した複数行の文字列 質問する

これが機能することはわかっています:

string multiline_text = @"this is a multiline text
this is line 1
this is line 2
this is line 3";

以下の作業を行うにはどうすればよいですか:

string a1 = " line number one";
string a2 = " line number two";
string a3 = " line number three";

string multiline_text = @"this is a multiline text
this is " + a1 + " 
this is " + a2 + " 
this is " + a3 + ";

文字列を各行ごとに 1 つずつ複数の部分文字列に分割せずに可能ですか?

ベストアンサー1

1 つのオプションは、代わりに文字列フォーマットを使用することです。C# 6 より前:

string pattern = @"this is a multiline text
this is {0}
this is {1}
this is {2}";

string result = string.Format(pattern, a1, a2, a3);

C# 6 では、補間された逐語的文字列リテラルを使用できます。

string pattern = $@"this is a multiline text
this is {a1}
this is {a2}
this is {a3}";

$@正確にそうする必要があることに注意してください。 を使用しようとすると@$、コンパイルされません。

おすすめ記事