C# 字符串拼接


C# 字符串拼接

在C#中,可以使用多种方法来拼接字符串,以下是几种常见的方法:

  1. 使用加号(+)操作符:

 
 
string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2; // "Hello World"
  1. 使用String.Concat方法:

 
 
string result = String.Concat(str1, " ", str2); // "Hello World"
  1. 使用字符串插值(C# 6.0+):

 
 
string result = $"{str1} {str2}"; // "Hello World"
  1. 使用StringBuilder类(适用于大量拼接操作):

 
 
StringBuilder sb = new StringBuilder();
sb.Append(str1);
sb.Append(" ");
sb.Append(str2);
string result = sb.ToString(); // "Hello World"
  1. 使用string.Format方法:

 
 
string result = string.Format("{0} {1}", str1, str2); // "Hello World"
  1. 使用$字符串插值符与string.Format结合(C# 6.0+):

 
 
string result = $"{str1} {str2}"; // "Hello World"

选择哪种方法取决于具体需求和场景。对于简单的拼接,使用加号操作符或字符串插值通常是最简洁的。对于大量或复杂的字符串操作,StringBuilder是性能上的优选。

posted on 2024-10-19 19:47  漫思  阅读(76)  评论(0编辑  收藏  举报

导航