vb.net 如何从字符串中删除空字符(零字符)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23693182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 17:31:04  来源:igfitidea点击:

How to remove null character (zero character) from string

vb.netunicodecharacter-encodingasciinull-character

提问by SSpoke

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

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.

对于每个字母,前面都有一个零字节(空字节)。我猜我必须使用某种 Unicode 编码或宽编码来获取没有那些零的文本。

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("
str = str.Replace(Convert.ToChar(0),"")
", "") 'Compiles and fails str = str.Replace(
Dim packet() As Byte = {&H0, &H44, &H0, &H65, &H0, &H6C, &H0, &H70, &H0, &H68, &H0, &H69}
Dim str As String = Encoding.BigEndianUnicode.GetString(packet)
, "") 'No compile str = str.Replace('
 str = str.Replace(vbNullChar, "")
', "") 'No compile

回答by Matt Wilko

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

如果你想要一些不依赖于 Microsoft.Visualbasic 命名空间的东西:

##代码##

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

唯一的选择是使用 String.Replace 我能想到的是使用正则表达式替换:http: //msdn.microsoft.com/en-us/library/844skk0h(v=vs.110) .aspx

回答by Remy Lebeau

The real problem is not the null bytes, but in how you are decoding the bytes ínto a Stringin the first place. You are using the wrong Encoding. You should be using Encoding.BigEndianUnicodeinstead 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:

真正的问题不是空字节,而是首先如何将字节解码为 a String。你用错了Encoding。您应该使用Encoding.BigEndianUnicode而不是Encoding.ASCII,那么您根本不需要手动替换空值,因为它们将由解码过程为您处理:

##代码##

回答by SSpoke

Solved it

解决了

##代码##

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

仍在寻找一种使用不依赖于Replace函数的内置函数来做到这一点的方法