Why string.IsNullOrWhiteSpace ("\ 0") is false

I had a problem when an invisible character \0that is quite similar to "white space", not considered a space by the string.IsNullOrWhiteSpace method. I wonder why this is implemented in .NET in this way and is there an alternative to string.IsNullOrWhiteSpace that can correctly handle a character with a null character? Thanks in advance.

+4
source share
6 answers

U + 0000 is not a space, basically. char.IsWhitespace('\0')returns false, it is not specified as a space ...

The zero part IsNullOrWhitespacerefers to the link to the string itself, and not to the content if that is what you were thinking about.

, .NET "" , CLR . ( , , , CLR , U + 0000 .) , \0, , , , .

+17

\0 , .

string.IsNullOrWhiteSpace("\0".Replace('\0', ' ');
+4

(, , , ), null ... / null ( null C) NUL ( null) \0.

String.IsNullOrWhiteSpace:

, , .

null, "null",

Unicode. IsNullOrWhiteSpace , true, Char.IsWhiteSpace .

, Char.IsWhiteSpace , Char.IsWhiteSpace.

+2

'\ 0' . . Char.IsWhitespace() , .

Enumerable.All(), . - :

bool IsMyKindOfWhiteSpace(string input)
{
    char[] more = new char[] { <here goes your list of additional white space chars> };

    return input.All(x => Char.IsWhiteSpace(x) || more.Contains(x));
}
+2
source

NULL string is NOT the same as empty string or space

0
source

Create an extension method that adds a null char as a check.

public bool IsNullOrWhitespaceOrHasNullChar(this string text)
{
   return string.IsNullOrWhiteSpace(text) || Regex.IsMatch(text, "\0");
}

Note that a null char value exists anywhere in the string, it will be found and reported as such, so the string with "a \ 0" will return true. If this is a concern, create a test that checks the complete string \0.

0
source

All Articles