I wanted to do trim by default white-space characters and by my additional characters. And I did this by following way:
string MyTrim(string source)
{
char[] badChars = { '!', '?', '#' };
var result = source.Trim().Trim(badChars);
return result == source
? result
: MyTrim(result);
}
As for me it is looks like stupid, because it has more iterations than it needs. Is it possible to add characters (instead replace defaults) for string.Trim()? Or where can I found array of 'default white-space characters' which is using in string.Trim() by default? It's sounds easy but I cannot found.
There is no way to change the default behavior of Trim
.
You can, however, if you must, create an array containing all the characters you want trimmed so that you can reduce the calls down to just one call, however it would be something like this:
var badChars =
(from codepoint in Enumerable.Range(0, 65536)
let ch = (char)codepoint
where char.IsWhiteSpace(ch)
|| ch == '!' || ch == '?' || ch == '#'
select ch).ToArray();
This will give you 1 call to Trim
:
var result = source.Trim(badChars);
Ideally you would store that badChars
somewhere so you don't have to build it all the time.
Now, will this be faster than two calls? I don't know, but I would measure it if necessary.
It is not possible to add additional characters directly.
However, the list of whitespace characters is defined here in the remarks and you could create a static helper list from all the enums provided.
Unless you are parsing enormous strings, it is probably not worth the effort to save a second pass on the string.
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