Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add characters (instead replace defaults) for string.Trim()?

Tags:

c#

.net

trim

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.

like image 316
Valentine Zakharenko Avatar asked Apr 16 '15 13:04

Valentine Zakharenko


2 Answers

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.

like image 176
Lasse V. Karlsen Avatar answered Nov 09 '22 20:11

Lasse V. Karlsen


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.

like image 27
Steve Mitcham Avatar answered Nov 09 '22 20:11

Steve Mitcham