Recipe 2.23. Pruning Characters from the Head and/or Tail of a StringProblemYou have a string with a specific set of characters, such as spaces, tabs, escaped single/double quotes, any type of punctuation character(s), or some other character(s), at the beginning and/or end of a string. You want a simple way to remove these characters. SolutionUse the trim, TrimEnd, or trimStart instance methods of the String class: string foo = "--TEST--"; Console.WriteLine(foo.Trim(new char[1] {'-'})); // Displays "TEST" foo = ",-TEST-,-"; Console.WriteLine(foo.Trim(new char[2] {'-',','})); // Displays "TEST" foo = "--TEST--"; Console.WriteLine(foo.TrimStart(new char[1] {'-'})); // Displays "TEST--" foo = ",-TEST-,-"; Console.WriteLine(foo.TrimStart(new char[2] {'-',','})); // Displays "TEST-,-" foo = "--TEST--"; Console.WriteLine(foo.TrimEnd(new char[1] {'-'})); // Displays "--TEST" foo = ",-TEST-,-"; Console.WriteLine(foo.TrimEnd(new char[2] {'-',','})); //Displays ",-TEST" DiscussionThe TRim method is most often used to eliminate whitespace at the beginning and end of a string. In fact, if you call trim without any parameters on a string variable, this is exactly what happens. The trim method is overloaded to allow you to remove other types of characters from the beginning and end of a string. You can pass in a char[] containing all the characters that you want removed from the beginning and end of a string. Note that if the characters contained in this char[] are located somewhere in the middle of the string, they are not removed. The TRimStart and trimEnd methods remove characters at the beginning and end of a string, respectively. These two methods are not overloaded, unlike the trim method. Rather, these two methods accept only a char[]. If you pass a null into either one of these methods, only whitespace is removed from the beginning or the end of a string. See AlsoSee the "String.Trim Method," "String.TrimStart Method," and "String.TrimEnd Method" topics in the MSDN documentation. |