
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
78
|
Chapter 2: Strings and 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 some-
where in the middle of the string, they are not removed.
The
TrimStart and TrimEnd methods remove characters at the beginning ...