How can I determine an empty string when its contents is \0\0\0\0
I have a SizeOfData variable of b开发者_如何学Cyte[4]
which returns:
byte[0] == 0
byte[1] == 0
byte[2] == 0
byte[3] == 0
When I do Encoding.ASCII.GetString(SizeOfData)
the string variable's length is 4 and String.IsNullOrEmpty()
returns false however when I look at the string in Visual Studio there is nothing in it.
How can I determine that if it contains all \0\0\0\0 then do X else Y?
A little bit of linq magic
if (bytes.All(b => b == 0))
or the slightly better
if (bytes.Any(b => b != 0))
when I look at the string in Visual Studio there is nothing in it
What you mean, I'm assuming, is that when you hover the mouse over the string in the debugger (or add a watch, or inspect the locals, or otherwise view a visual representation of the string) it appears to be empty. This is because \0
, like some other characters, is a non-printable character. These characters are there, but they do not cause a visual effect.
If you want to determine if the byte array is only zero, that's simple:
(Note that your array name above is invalid, so I'm going to call it data
)
if(data.Add(b => b == 0))
{
// is only null characters
}
However, it seems like you'd want something a bit more robust, and something that could work on strings. You can use a simple RegEx to replace the range of non-printable Unicode characters (your original string as in ASCII, I know, but once you parse it it's stored internally as UTF-16):
yourString = Regex.Replace(yourString, "[\x00-\x1F]", "");
At this point, string.IsNullOrEmpty(yourString)
should return true
.
Before converting to string you could:
bool isNulls = SizeOfData.All(x => x == 0);
If you can handle it earlier, you could check the byte array:
if(SizeOfData.Any(b => b != 0))
// do something
else
// do something else
精彩评论