温馨提示×

c#字符串拼接的几种方式

c#
小亿
94
2024-08-17 12:39:35
栏目: 编程语言

在C#中,有多种方法可以用于字符串拼接:

  1. 使用加号 + 操作符:
string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2;
Console.WriteLine(result); // Output: Hello World
  1. 使用字符串插值:
string str1 = "Hello";
string str2 = "World";
string result = $"{str1} {str2}";
Console.WriteLine(result); // Output: Hello World
  1. 使用 string.Concat 方法:
string str1 = "Hello";
string str2 = "World";
string result = string.Concat(str1, " ", str2);
Console.WriteLine(result); // Output: Hello World
  1. 使用 StringBuilder 类:
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");
string result = sb.ToString();
Console.WriteLine(result); // Output: Hello World

这些都是常见的方法用于字符串拼接,具体使用哪种取决于个人偏好和实际需求。

0