Mega Code Archive

 
Categories / C# Book / 02 Essential Types
 

0241 Trim a string

Trim, TrimStart, TrimEnd remove specified characters from a string. TrimStart removes the characters from the start of a string. TrimEnd deletes the characters from the end of a string. Trim does the trim from both ends. using System; class Sample { public static void Main() { string s = " rntsoft.com "; Console.WriteLine("=" + s.Trim() + "="); Console.WriteLine("=" + s.TrimStart() + "="); Console.WriteLine("=" + s.TrimEnd() + "="); } } The output: =rntsoft.com= =rntsoft.com = = rntsoft.com= By default these functions remove while spaces including tabs and new lines. We can passin characters to those functions. using System; class Sample { public static void Main() { string s = "rntsoft.com"; Console.WriteLine("=" + s.Trim('m') + "="); Console.WriteLine("=" + s.TrimStart('j') + "="); Console.WriteLine("=" + s.TrimEnd('m') + "="); } }