The Trim() method in C# is used to return a new string in which all leading and trailing occurrences of a set of specified characters from the current string are removed.
Syntax
public string Trim (); public string Trim (params char[] trimChars);
Above, the trimChars parameter is an array of Unicode characters to remove, or null.
Example
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 (after trim) = "+str1.Trim());
Console.WriteLine("String1 ToUpper = "+str1.ToUpper(new CultureInfo("en-US", false)));
Console.WriteLine("String1 Substring from index4 = " + str1.Substring(2, 2));
Console.WriteLine("\n\nString2 = "+str2);
Console.WriteLine("String2 ToUpper = "+str2.ToUpper(new CultureInfo("en-US", false)));
Console.WriteLine("String2 Substring from index2 = " + str2.Substring(0, 5));
}
}Output
String1 = JackSparrow! String1 (after trim) = JackSparrow! String1 ToUpper = JACKSPARROW! String1 Substring from index4 = String2 = @#$PQRSTUV! String2 ToUpper = @#$PQRSTUV! String2 Substring from index2 = @
Example
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 (after trim) = " + str.Trim(arr));
}
}Output
String = JackSparrow! String (after trim) = ckSparrow!