要在C#中并置字符串,请使用String.Concat()方法。
public static string Concat (string str1, string str2);
上面的参数str1和str2是要串联的字符串。
using System; public class Demo { public static void Main(String[] args) { string str1 = "Jack"; string str2 = "Sparrow"; Console.WriteLine("String 1 = "+str1); Console.WriteLine("HashCode of String 1 = "+str1.GetHashCode()); Console.WriteLine("Does String1 begins with E? = "+str1.StartsWith("E")); Console.WriteLine("\nString 2 = "+str2); Console.WriteLine("HashCode of String 2 = "+str2.GetHashCode()); Console.WriteLine("Does String2 begins with E? = "+str2.StartsWith("E")); Console.WriteLine("\nString 1 is equal to String 2? = {0}", str1.Equals(str2)); Console.WriteLine("Concatenation Result = "+String.Concat(str1,str2)); } }
输出结果
String 1 = Jack HashCode of String 1 = 1167841345 Does String1 begins with E? = False String 2 = Sparrow HashCode of String 2 = -359606417 Does String2 begins with E? = False String 1 is equal to String 2? = False Concatenation Result = JackSparrow
现在让我们看另一个示例,其中我们将concat()
仅使用单个参数使用该方法。
public static string Concat (params string[] arr);
上面的arr是字符串数组。
using System; public class Demo { public static void Main(string[] args) { string[] strArr = {"This", "is", "it", "!" }; Console.WriteLine("String Array..."); foreach(string s in strArr) { Console.WriteLine(s); } Console.WriteLine("Concatenation = {0}",string.Concat(strArr)); string str = string.Join("/", strArr); Console.WriteLine("Result (after joining) = " + str); } }
输出结果
String Array... This is it ! Concatenation = Thisisit! Result (after joining) = This/is/it/!