3

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.

3
  • "leading whitespace" means you want to use TrimStart Commented Dec 2, 2014 at 17:00
  • There's nothing wrong with this question. +1 to compensate for downvote. Commented Dec 2, 2014 at 17:02
  • Fair enough, but I didn't see a close vote for the dupe, or a comment to that effect. I found the question valuable, since, in all these years of coding C# I had never hit upon Trim() having parms -- never needed it, I guess. Commented Dec 2, 2014 at 17:07

1 Answer 1

10

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" 
Sign up to request clarification or add additional context in comments.

3 Comments

Actually this didn't work because in my case the leading characters are tabs and perhaps other whitespace characters. I needed something that represented the equivalent of Trim(). I suppose I could add all whitespace characters?
@user2449323 Sure (there are 25 of them according to the link in my answer), or just specify tab or just call Trim twice (which would be cleaner IMHO than specifying 25 characters to trim).
Calling Trim twice doesn't work either if your string starts with - - - - or something. You'd have to stick it in a loop and check if it still needs to be trimmed of all chars. Trim should allow for a whitespace escape char like Regex's \s

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.