The String
class in the Namespace System
provides the Trim()
method with multiple overloads. Trim(char[])
returns a new instance of a string in which all the leading and trailing occurrences of a set of characters provided by the caller are removed.
public string Trim (params char[]? trimChars);
params
parameter.Trim()
returns a new string with the remaining characters and does not modify the existing string instance.Input | trimChars | Output |
---|---|---|
“aaabbbaaa” | [‘a’] | bbb |
“abccccccab” | [‘a’,‘b’] | cccccc |
" abc cab" | [] | “abc cab” |
Here, we are calling the Trim()
method to remove the leading and trailing underscore and hyphen characters from a username. Notice that the underscore and hyphen in the middle of the string remain unmodified.
Initial UserName : __high_sky-user----
After removing leading and trailing _ and - : high_sky-user
using System;class HelloWorld{static void Main(){//Let's remove all leading and trailing underscores and hyphens from the usernamechar[] trimChars = { '-', '_' };string userName = "__high_sky-user----";string output = userName.Trim(trimChars);Console.WriteLine("Initial UserName : {0} \nAfter removing leading and trailing _ and - : {1}",userName, output);}}
The String class also has Trim(char)
and Trim()
overloads, which are used to remove the leading and trailing occurrences of single characters and whitespaces, respectively.
Trim(char)
removes the leading and trailing occurrences of the input character from a string and returns a new string. Each leading and trailing trim operation is stopped when a character other than the input character is encountered.
public string Trim (char trimChar);
If the string is empty or all of the characters are equal to the trimChar, Trim(char)
returns an empty string.
Trim()
removes the leading and trailing occurrences of whitespaces from a string and returns a new string. Each leading and trailing trim operation is stopped when a character other than a whitespace is encountered.
public string Trim ();
using System;public class StringTrimmer{public static void Main(){string input1 = "1111hello1111111";Console.WriteLine("original : {0} \nAfter Trim('1') : {1}",input1, input1.Trim('1'));// output : hellostring input2 = "www.testwwtest.ew";Console.WriteLine("original : {0} \nAfter Trim('w') : {1}",input2, input2.Trim('w'));// output : .testwwtest.estring input3 = " hello ";Console.WriteLine("original : {0} \nAfter Trim() : {1}", input3, input3.Trim());// output : hello}}
The
Trim()
method is very useful for removing additional whitespaces from user input.