Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I faced a problem where invisible character \0 which is pretty like a 'white space' not considered as white space by the string.IsNullOrWhiteSpace method. I wonder why this implemented in .NET in so manner and is there any alternative to string.IsNullOrWhiteSpace which can properly handle null-terminate character? Thanks in advance.

like image 359
Shoar Avatar asked Jun 25 '15 14:06

Shoar


2 Answers

U+0000 isn't whitespace, basically. char.IsWhitespace('\0') returns false, it's not listed as whitespace...

The null part of IsNullOrWhitespace refers to the string reference itself - not the contents, if that's what you were thinking of.

Note that strings in .NET aren't logically "null-terminated" within managed code, although in practice at the CLR level they are, for interop purposes. (The string knows its own length, but in order to make it easier to work with native code which does expect a null terminator, the CLR ensures that there's always a U+0000 after the content of the string.) If you end up with a string containing \0 you should probably fix whatever produced it to start with.

like image 174
Jon Skeet Avatar answered Nov 08 '22 17:11

Jon Skeet


You could replace all \0 characters with the space character, and then check for whitespace.

string.IsNullOrWhiteSpace("\0".Replace('\0', ' ');
like image 36
Cyral Avatar answered Nov 08 '22 18:11

Cyral