For example, if I want to remove whitespace and trailing commas from a string, I can do this:
String x = "abc,\n";
x.Trim().Trim(new char[] { ',' });
which outputs abc
correctly. I could easily wrap this in an extension method, but I'm wondering if there is an in-built way of doing this with a single call to Trim()
that I'm missing. I'm used to Python, where I could do this:
import string
x = "abc,\n"
x.strip(string.whitespace + ",")
The documentation states that all Unicode whitespace characters, with a few exceptions, are stripped (see Notes to Callers section), but I'm wondering if there is a way to do this without manually defining a character array in an extension method.
Is there an in-built way to do this? The number of non-whitespace characters I want to strip may vary and won't necessarily include commas, and I want to remove all whitespace, not just \n
.
Yes, you can do this:
x.Trim(new char[] { '\n', '\t', ' ', ',' });
Because newline is technically a character, you can add it to the array and avoid two calls to Trim
.
EDIT
.NET 4.0 uses this method to determine if a character is considered whitespace. Earlier versions maintain an internal list of whitespace characters (Source).
If you really want to only use one Trim
call, then your application could do the following:
Char.IsWhiteSpace
on each character.Now you can use a single Trim
call, by passing the array you constructed.
I'm guessing that Char.IsWhiteSpace
depends on the current locale, so you'll have to pay careful attention to locale.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With