How to remove null character (zero character) from string

24,229

Solution 1

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)

Solution 2

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

Solution 3

Solved it

 str = str.Replace(vbNullChar, "")

Still looking for a way to do this with a built-in function not relying on Replace function

Share:
24,229
SSpoke
Author by

SSpoke

Pro programmer from the russia How to be a programmer in steps? 1). Set a goal what you wish to program.. 2). Make your program just work. (don't worry think much how messy your coding is.) 3). Fix all bugs you can find and do tests on each part to make sure no more bugs exist. 4). Finally start from scratch and re-write your program in a clean matter, this will be fast don't worry because you already did this once ;). 4). And always ask StackOverflow for advise on parts you are unsure.

Updated on June 06, 2020

Comments

  • SSpoke
    SSpoke almost 4 years

    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