如何:串連多個字串 (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 方法。 + 運算子簡單易用,且容易建立直覺化程式碼。 即使一個陳述式使用數個 + 運算子,字串內容也只會複製一次。 下列程式碼示範使用 ++= 運算子來串連字串的範例:

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.ConcatString.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

最後,您可以使用 LINQEnumerable.Aggregate 方法從集合加入字串。 這個方法使用 Lambda 運算式結合來源字串。 Lambda 運算式會負責將各個字串新增到目前累積的內容。 下列範例透過在陣列中的每個字之間新增空格,結合一個陣列的字組:

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

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

這個選項可能會造成比其他方法更多的配置來串連集合,因為這會為每個反覆項目建立中繼字串。 如果最佳化效能很重要,請考慮 StringBuilder類別或 String.ConcatString.Join 方法來串連集合,而不是 Enumerable.Aggregate

另請參閱