C# 字符串 - Concat() 方法
C# 字符串 Concat() 方法用于将两个或多个字符串连接或合并为一个字符串。它支持数组和其他对象的连接。
语法
以下是 C# 字符串 Concat() 方法的语法 -
基本连接:
public static string Concat(string? str1, string? str2);
连接三个字符串:
public static string Concat(string? str1, string? str2, string? str3);
连接多个字符串:
public static string Concat(params string?[] values);
连接对象:
public static string Concat(params object?[] args);
参数
此方法接受多个字符串、对象和数组进行连接。
返回值
此方法返回一个字符串,它是多个字符串的连接结果。
示例 1:连接两个字符串
这是字符串 Concat() 方法的基本示例。在这里,我们将两个字符串连接成一个字符串。
using System; class Program { static void Main() { string str1 = "abcdef"; string str2 = "abcxyz"; // 连接两个字符串 string result = String.Concat(str1, str2); Console.WriteLine("concatenated: " + result); } }
输出
以下是输出 -
concatenated: abcdefabcxyz
示例 2:连接三个字符串
让我们看另一个 Concat() 方法的示例。在这里,我们使用此方法将三个字符串连接成一个字符串 -
using System; class Program { static void Main() { string str1 = "abcdef"; string str2 = " abcxyz"; string str3 = "Aman "; // 连接三个字符串 string result = String.Concat(str3, str1, str2); Console.WriteLine("concatenated: " + result); } }
输出
以下是输出 -
示例 3:连接对象
在下面的示例中,我们使用 Concat() 方法连接两个以上的对象,所有对象都是不同类型的。−
using System; class Program { static void Main() { int number = 42; double pi = 3.14; string text = "The answer is "; string result = String.Concat(text, number, " and pi is approximately ", pi); Console.WriteLine(result); } }
输出
以下是输出 -
The answer is 42 and pi is approximately 3.14
示例 4:连接数组元素
在此示例中,我们使用另一个版本的 Concat() 方法来连接字符串数组 -
using System; class Program { static void Main() { string[] words = { "This ", "is ", "a ", "tutorialspoint." }; string result = String.Concat(words); Console.WriteLine(result); } }
输出
以下是输出 -
This is a tutorialspoint.