Is it possible to add characters (instead of the default replacement) for string.Trim ()?

I wanted to truncate the default space characters and my extra characters. And I did it as follows:

string MyTrim(string source) { char[] badChars = { '!', '?', '#' }; var result = source.Trim().Trim(badChars); return result == source ? result : MyTrim(result); } 

For me, this looks silly because it has more iterations than necessary. Is it possible to add characters (instead of the default replacement) for string.Trim ()? Or where can I find the array of "white spaces by default" that is used by default in string.Trim ()? It sounds simple, but I can not find.

+6
source share
3 answers

Cannot change the default behavior of Trim .

However, you can create an array containing all the characters you want to trim to reduce the number of calls to one call, however it will 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 Trim call:

 var result = source.Trim(badChars); 

Ideally, you would keep this badChars somewhere, so you don’t have to constantly create it.

Now, will it be faster than two calls? I don’t know, but I would measure it if necessary.

+10
source

Cannot add additional characters directly.

However, a list of space characters is defined here in the notes , and you can create a static helper list from all the enumerations provided.

If you don't parse huge lines, you probably shouldn't try to keep the second pass in a line.

+1
source
 string MyTrim(string source) { if (_badChars == null) _badChars = Enumerable .Range(0, char.MaxValue) .Cast<char>() .Where(chr => char.IsWhiteSpace(chr) || chr == '!' || chr == '?' || chr == '#') .ToArray(); return source.Trim(_badChars); } 
0
source

Source: https://habr.com/ru/post/985265/


All Articles