C#中的Join()方法用于连接字符串数组的所有元素,并在每个元素之间使用指定的分隔符。
语法如下-
public static string Join (string separator, string[] val);
在上方,分隔符是包含在字符串中的分隔符。val参数是包含要连接的元素的数组。
现在让我们看一个例子-
using System; public class Demo { public static void Main(string[] args) { string[] strArr = {"One", "Two", "Three", "Four" }; Console.WriteLine("String Array..."); foreach(string s in strArr) { Console.WriteLine(s); } string str = string.Join("/", strArr); Console.WriteLine("Result (after joining) = " + str); } }
输出结果
这将产生以下输出-
String Array... One Two Three Four Result (after joining) = One/Two/Three/Four
现在让我们来看另一个例子-
using System; public class Demo { public static void Main(string[] args) { string[] strArr = {"AB", "BC", "CD", "DE", "EF", "FG", "GH", "IJ" }; Console.WriteLine("String Array..."); foreach(string s in strArr) { Console.WriteLine(s); } string str = string.Join("*", strArr); Console.WriteLine("Result (after joining) = " + str); } }
输出结果
这将产生以下输出-
String Array... AB BC CD DE EF FG GH IJ Result (after joining) = AB*BC*CD*DE*EF*FG*GH*IJ