C# How to trim both whitespace character and other character

c#

Solution

Use the overload of `Trim` that accepts multiple characters:

string s = "    'hello'";
var newString = s.Trim(' ', '\'');

Although there are several caveats:

- your question only mentions leading whitespace, but `Trim` removes trailing characters as well. If you only want leading characters use `TrimStart` instead.

- this solution only removes full spaces, not all whitespace. Technically you would have to add all characters that are considered "whitespace". If you need to trim more than just spaces, then calling `Trim` twice will be cleaner.

This solution would also Trim whitespace within the apostrophes:

string s = "  '  hello'";
var newString = s.Trim(' ', '\'');   // returns "hello"

Problem

I want to trim leading whitespace and the single quote using one call to Trim without calling it twice as follows. ``` string s = " 'hello'"; var newString = s.Trim().Trim('\''); ``` I don't want to use ``` var newString = s.TrimStart().Trim(''\'). ``` either as it is two calls.

Original source

Related problems