C# 字符串连接示例
在 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("
String 2 = "+str2); Console.WriteLine("HashCode of String 2 = "+str2.GetHashCode()); Console.WriteLine("Does String2 begins with E? = "+str2.StartsWith("E")); Console.WriteLine("
String 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/!
广告