C#两个 string拼接
时间: 2023-09-26 11:06:50 浏览: 79
在C#中,你可以使用`+`运算符或`string.Concat`方法来拼接两个字符串。
下面是使用`+`运算符拼接字符串的示例:
```csharp
string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2;
Console.WriteLine(result); // 输出:Hello World
```
上面的代码将`str1`和`str2`两个字符串通过`+`运算符进行拼接,并将结果赋值给`result`变量。
另外,你还可以使用`string.Concat`方法来拼接多个字符串:
```csharp
string str1 = "Hello";
string str2 = "World";
string result = string.Concat(str1, " ", str2);
Console.WriteLine(result); // 输出:Hello World
```
`string.Concat`方法可以接受多个字符串参数,并将它们按顺序拼接在一起。
无论是使用`+`运算符还是`string.Concat`方法,都会创建一个新的字符串对象来保存拼接后的结果。如果你需要频繁进行字符串拼接操作,建议使用`StringBuilder`类来提高性能。
相关问题
两个string[]怎么相加 c#
两个string[]可以通过使用数组拼接的方法进行相加。具体做法是创建一个新的string[],将两个原始的string[]按顺序添加到新数组中,最终得到相加后的结果。以下是示例代码:
```
string[] arr1 = {"Hello", "world"};
string[] arr2 = {"I", "am", "a", "chatbot"};
string[] arr3 = new string[arr1.Length + arr2.Length];
arr1.CopyTo(arr3, 0);
arr2.CopyTo(arr3, arr1.Length);
```
通过上述代码,将arr1和arr2相加后,存储在arr3中,最终结果为{"Hello", "world", "I", "am", "a", "chatbot"}。
string拼接使用加号
在C#中,可以使用加号(+)来拼接字符串。这个操作符可以用于将两个字符串连接成一个新的字符串。例如:
```csharp
string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2; // 输出:Hello World
```
在上面的示例中,我们使用加号将两个字符串 `str1` 和 `str2` 连接起来,并将结果存储在 `result` 变量中。注意,在字符串之间添加空格可以使用空格字符 `" "`。
除了加号操作符,还可以使用 `String.Concat` 方法来拼接多个字符串。例如:
```csharp
string str1 = "Hello";
string str2 = "World";
string result = String.Concat(str1, " ", str2); // 输出:Hello World
```
使用加号或 `String.Concat` 方法都可以完成字符串的拼接操作。选择哪种方法取决于个人的喜好和具体的需求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)