C#中的Trim()方法用于返回新字符串,该字符串中删除了当前字符串中一组指定字符的所有开头和结尾。
public string Trim (); public string Trim (params char[] trimChars);
在上面,trimChars参数是一个要删除的Unicode字符数组,或者为null。
using System; using System.Globalization; public class Demo { public static void Main(String[] args) { string str1 = " JackSparrow!"; string str2 = " @#$PQRSTUV!"; Console.WriteLine("String1 = "+str1); Console.WriteLine("String1 (修剪后) = "+str1.Trim()); Console.WriteLine("String1 转换为大写= "+str1.ToUpper(new CultureInfo("en-US", false))); Console.WriteLine("String1子字符串从索引4 = " + str1.Substring(2, 2)); Console.WriteLine("\n\nString2 = "+str2); Console.WriteLine("String2 转换为大写= "+str2.ToUpper(new CultureInfo("en-US", false))); Console.WriteLine("String2子字符串从索引5 = " + str2.Substring(0, 5)); } }
输出结果
String1 = JackSparrow! String1 (修剪后) = JackSparrow! String1 转换为大写= JACKSPARROW! String1子字符串从索引4 = String2 = @#$PQRSTUV! String2 转换为大写= @#$PQRSTUV! String2子字符串从索引5 = @
using System; public class Demo { public static void Main(String[] args) { string str = "JackSparrow!"; char[] arr = { 'J', 'a'}; Console.WriteLine("String = "+str); Console.WriteLine("String (修剪后) = " + str.Trim(arr)); } }
输出结果
String = JackSparrow! String (修剪后) = ckSparrow!