Strings and Characters, Part 2 - 2.23 Pruning Characters from the Head and/or Tail of a String
(Page 11 of 11 )
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 would happen. 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, similar to 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.
 | If you've enjoyed what you've seen here, or to get more information, click on the "Buy the book!" graphic. Pick up a copy today!
Visit the O'Reilly Network http://www.oreillynet.com for more online content. |
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |