简体   繁体   中英

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

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

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)

Solved it

 str = str.Replace(vbNullChar, "")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM