如何连接多个字符串(C# 指南)

串联是将一个字符串追加到另一字符串末尾的过程。 可使用 + 运算符连接字符串。 对于字符串文本和字符串常量,会在编译时进行串联,运行时不串联。 对于字符串变量,仅在运行时串联。

小贴士

可以使用 AI 帮助连接 字符串

字符串文本

以下示例将长字符串字面量拆分为较短的字符串,从而提高源代码的可读性。 以下代码将较短的字符串连接起来,以创建长字符串字面量。 在编译时将这些部分连接成一个字符串。 无论涉及到多少个字符串,均不产生运行时性能开销。

// 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.";

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 + ".";
Console.WriteLine(str);

str += " How are you today?";
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}.";
Console.WriteLine(str);

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

注意

在字符串串联操作中,C# 编译器将 null 字符串视为空字符串进行处理。

当用于占位符的所有表达式也是常量字符串时,可以使用字符串内插来初始化常量字符串。

String.Format

另一个字符串连接方法为 String.Format。 从几个组件字符串生成字符串时,此方法非常有效。

StringBuilder

在其他情况下,你可能会在循环中组合字符串,其中源字符串的实际数量可能很大。 StringBuilder 类专门用于此类方案。 以下代码使用 Append 类的 StringBuilder 方法串联字符串。

// Use StringBuilder for concatenation in tight loops.
var sb = new StringBuilder();
for (int i = 0; i < 20; i++)
{
    sb.AppendLine(i.ToString());
}
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);
Console.WriteLine(unreadablePhrase);

var readablePhrase = string.Join(" ", words);
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}");
Console.WriteLine(phrase);

此选项可能会比其他连接集合的方法导致更多内存资源的分配,因为它在每次迭代时都会创建一个中间字符串。 如果优化性能至关重要,请考虑使用 StringBuilder 类或 String.ConcatString.Join 方法来连接集合,而不是使用 Enumerable.Aggregate

使用 AI 连接字符串

可以使用 AI 工具(如 GitHub Copilot)生成 C# 代码来连接字符串。 可以自定义提示以指定输出格式、变量和根据要求使用的方法。

下面是 Copilot Chat 提示示例:

Generate C# code to use string interpolation to build an output string:
"Hello [name], today's date is [current date]. You have [count] new notifications."
Use variables for: name is "John", date is today's date, and notification count is 3.
Format the date as mm/dd/yyyy.
Show the output.

在应用 Copilot 之前,请查看 Copilot 的建议。

有关详细信息,请参阅 Copilot 常见问题解答

另请参阅