VB.NET - string of nulls

WizardsSleeve picture WizardsSleeve · Jun 29, 2010 · Viewed 11.8k times · Source

I have a string value read in from a CSV file. The CSV file contains 7 NULL bytes, I have confirmed this by opening it in a hex editor and sure enought there are 7 0x0 bytes in there. This string is causing me pain.

In vb.net when I check the strlen of this string it returns a value of 7 and if i do a String.IsNullOrWhitespace it returns false.

I cannot understand why this is? I have split the string into a byte array and each byte is 0x0, which is null/nothing. A string = Nothing comparison also fails.

I want to be able to replace this string with a string of my own but I cannot do this dynamically. Any suggestions why this string returns a length of 7 even though each byte is 0x0?

Answer

C. Ross picture C. Ross · Jun 29, 2010

Unfortunately the null character seven times is not an empty string, or a null string. Remember in .NET a string is at some level a pointer to a character array. A string is null if this pointer is set to null. A string is empty if the pointer points to a zero length array. In this case the pointer points to a length seven array of null characters (the byte being all zeros).

Null String

A ->

Empty String

A -> ()

Your String

A -> ((0)(0)(0)(0)(0)(0)(0))

You can test for this null character by using

char nullChar = char.ConvertFromUtf32(0);
string nullCharString = new String(nullChar);
bool hasNullChar = A.Contains(nullCharString);