2.16. 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[] {'-'})); // Displays "TEST"
foo = ",-TEST-,-";
Console.WriteLine(foo.Trim(new char[] {'-',','})); // Displays "TEST"
foo = "--TEST--";
Console.WriteLine(foo.TrimStart(new char[] {'-'})); // Displays "TEST--"
foo = ",-TEST-,-";
Console.WriteLine(foo.TrimStart(new char[] {'-',','})); // Displays "TEST-,-"
foo = "--TEST--";
Console.WriteLine(foo.TrimEnd(new char[] {'-'})); // Displays "--TEST"
foo = ",-TEST-,-";
Console.WriteLine(foo.TrimEnd(new char[] {'-',','})); // 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access