vb.net - 将字符串编码为 UTF-8
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6035380/
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
vb.net - Encode string to UTF-8
提问by thom
I've made a class to encode a string
我做了一个类来编码一个字符串
Public Class UTF8
Public Shared Function encode(ByVal str As String)
Dim utf8Encoding As New System.Text.UTF8Encoding
Dim encodedString() As Byte
encodedString = utf8Encoding.GetBytes(str)
Return encodedString.ToString()
End Function
End Class
Return encodedString.ToString() always returns "System.Byte[]". How could I get the real UTF-8 String?
返回 encodeString.ToString() 总是返回“System.Byte[]”。我怎样才能得到真正的 UTF-8 字符串?
回答by Alireza Maddah
Use UTF8.GetString(Byte[])method.
回答by Predator
We can check if a string is UTF-8 by examining the string BOM value. This is the correct code sample:
我们可以通过检查字符串 BOM 值来检查字符串是否为 UTF-8。这是正确的代码示例:
Public Shared Function encode(ByVal str As String) As String
'supply True as the construction parameter to indicate
'that you wanted the class to emit BOM (Byte Order Mark)
'NOTE: this BOM value is the indicator of a UTF-8 string
Dim utf8Encoding As New System.Text.UTF8Encoding(True)
Dim encodedString() As Byte
encodedString = utf8Encoding.GetBytes(str)
Return utf8Encoding.GetString(encodedString)
End Function

