How to remove null character (zero character) from string

SSpoke picture SSpoke · May 16, 2014 · Viewed 24.1k times · Source

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

Matt Wilko picture Matt Wilko · May 16, 2014

If you want something that doesn't rely on the Microsoft.Visualbasic namespace:

str = str.Replace(Convert.ToChar(0),"")

The only alternative is to using String.Replace I can think of is to use a regex replace: http://msdn.microsoft.com/en-us/library/844skk0h(v=vs.110).aspx