[英]String.IsNullOrEmpty is not detecting the Escape sequence NULL \0 in C#
I tried the following if statement but if fails to detect the NULL 我尝试了以下if语句但是如果无法检测到NULL
void Main()
{
string str = "\0".Trim();
if (string.IsNullOrEmpty(str))
{
"Empty".Dump();
}
else
{
"Non-Empty".Dump();
}
}
Kindly refer the LinqPad snapshot 请参考LinqPad快照
I got the output 我得到了输出
Non-Empty
I don't know how its failing. 我不知道它是怎么失败的。 Kindly assist me.
请帮助我。
Your string contains one character \\0
. 您的字符串包含一个字符
\\0
。
This character is non-printable, so you don't see it in Watches, but if you add str.Length
to watches, you will see "1". 此字符是不可打印的,因此您在Watches中看不到它,但如果将
str.Length
添加到str.Length
中,您将看到“1”。
So, is your string null? 那么,你的字符串是否为空? Definitely, no.
绝对没有。 Is it empty?
它是空的吗? No, it contains characters.
不,它包含字符。
Hence, string.IsNullOrEmpty
logically results into false
and it outputs "Non-Empty". 因此,
string.IsNullOrEmpty
逻辑上导致为false
,并输出“Non-Empty”。
If for some reason you receive strings containing \\0
characters and want to treat it as an empty string, you can just trim \\0
as well: 如果由于某种原因你收到包含
\\0
字符的字符串并希望将其视为空字符串,你也可以修剪\\0
:
string str = "\0".Trim(new[] { '\0', ' ', '\t' });
if (string.IsNullOrEmpty(str))
{
"Empty".Dump();
}
else
{
"Non-Empty".Dump();
}
This will output "Empty". 这将输出“Empty”。
As suggested by Patrick Hofman, it is better to use string.IsNullOrWhiteSpace
since it is more suitable for this case and can handle a wider range of white-space, non-visible, BOM characters etc.. 正如Patrick Hofman所建议的那样,最好使用
string.IsNullOrWhiteSpace
因为它更适合这种情况,并且可以处理更广泛的空白,不可见,BOM字符等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.