C# 字符串拼接
C# 字符串拼接
在C#中,可以使用多种方法来拼接字符串,以下是几种常见的方法:
-
使用加号(
+
)操作符:
string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2; // "Hello World"
-
使用
String.Concat
方法:
string result = String.Concat(str1, " ", str2); // "Hello World"
-
使用字符串插值(C# 6.0+):
string result = $"{str1} {str2}"; // "Hello World"
-
使用
StringBuilder
类(适用于大量拼接操作):
StringBuilder sb = new StringBuilder();
sb.Append(str1);
sb.Append(" ");
sb.Append(str2);
string result = sb.ToString(); // "Hello World"
-
使用
string.Format
方法:
string result = string.Format("{0} {1}", str1, str2); // "Hello World"
-
使用
$
字符串插值符与string.Format
结合(C# 6.0+):
string result = $"{str1} {str2}"; // "Hello World"
选择哪种方法取决于具体需求和场景。对于简单的拼接,使用加号操作符或字符串插值通常是最简洁的。对于大量或复杂的字符串操作,StringBuilder
是性能上的优选。
漫思