Recipe2.23.Pruning Characters from the Head andor Tail of a String


Recipe 2.23. Pruning Characters from the Head and/or Tail of a String

Problem

You 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.

Solution

Use 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" 

Discussion

The 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 Also

See the "String.Trim Method," "String.TrimStart Method," and "String.TrimEnd Method" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net