SSpoke SSpoke - 1 year ago 140 Question

How to remove null character (zero character) from string

I been trying to remove all the zero characters from my string

My string is made from these hexadecimal bytes

00 44 00 65 00 6C 00 70 00 68 00 69

For every letter there is a Zero byte (null byte) in front of it.. I was guessing I had to use some kind of Unicode encoding or wide encoding to get the text without those zero's.

But I couldn't figure it out so I figured best way is to use a Replace but even that fails.

Dim packet() As String = {&H0, &H44, &H0, &H65, &H0, &H6C, &H0, &H70, &H0, &H68, &H0, &H69}
Dim str As String = Encoding.ASCII.GetString(packet, 0, 12)
str = str.Replace("\0", "") 'Compiles and fails
str = str.Replace(\0, "") 'No compile
str = str.Replace('\0', "") 'No compile

Answer Source

The real problem is not the null bytes, but in how you are decoding the bytes ├Źnto a String in the first place. You are using the wrong Encoding. You should be using Encoding.BigEndianUnicode instead of Encoding.ASCII, then you don't need to replace the nulls manually at all as they will be handled for you by the decoding process:

Dim packet() As Byte = {&H0, &H44, &H0, &H65, &H0, &H6C, &H0, &H70, &H0, &H68, &H0, &H69}
Dim str As String = Encoding.BigEndianUnicode.GetString(packet)