vb.net - Encode string to UTF-8

故事扮演 提交于 2019-12-01 07:44:07

问题


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?


回答1:


Use UTF8.GetString(Byte[]) method.




回答2:


We can check if a string is UTF-8 by examining the string BOM value. This is the correct code sample:

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


来源:https://stackoverflow.com/questions/6035380/vb-net-encode-string-to-utf-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!