Jon
Jon

Reputation: 40032

How can I determine an empty string when its contents is \0\0\0\0

I have a SizeOfData variable of byte[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?

Upvotes: 1

Views: 259

Answers (4)

Adam Robinson
Adam Robinson

Reputation: 185643

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.

Upvotes: 2

Mikael Östberg
Mikael Östberg

Reputation: 17156

If you can handle it earlier, you could check the byte array:

if(SizeOfData.Any(b => b != 0))
    // do something
else
    // do something else

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

Before converting to string you could:

bool isNulls = SizeOfData.All(x => x == 0);

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190941

A little bit of linq magic

if (bytes.All(b => b == 0))

or the slightly better

if (bytes.Any(b => b != 0))

Upvotes: 4

Related Questions