我正在尝试将UTF-8编码的字符串转换为VB中的windows-1255。没有运气。NET。诚然,我不懂VB,但我试过在MSDN上使用一个例子,并根据我的需要修改它:
Public Function Utf82Hebrew(ByVal Str As String) As String
Dim ascii As Encoding = Encoding.GetEncoding("windows-1255")
Dim unicode As Encoding = Encoding.Unicode
' Convert the string into a byte array.
Dim unicodeBytes As Byte() = unicode.GetBytes(Str)
' Perform the conversion from one encoding to the other.
Dim asciiBytes As Byte() = Encoding.Convert(unicode, ascii, unicodeBytes)
' Convert the new byte array into a char array and then into a string.
Dim asciiChars(ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)-1) As Char
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0)
Dim asciiString As New String(asciiChars)
Utf82Hebrew = asciiString
End Function
这个函数实际上不做任何事情——字符串仍然是UTF-8格式。但是,如果我改变这一行:
Dim ascii As Encoding = Encoding.GetEncoding("windows-1255")
:
Dim ascii As Encoding = Encoding.ASCII
则该函数在字符串的位置返回问号。
有没有人知道如何正确地将UTF-8字符串转换为特定的编码(在这种情况下,windows-1255),和/或我在上述代码中做错了什么?
我修改了你的代码将文本从一种编码转换为另一种编码非常简单。在VB.Net中应该这样做。Windows文件编码是1252,而不是1255。
Public Function Utf82Hebrew(ByVal Str As String) As String
Dim ascii As System.Text.Encoding = System.Text.Encoding.GetEncoding("1252")
Dim unicode As System.Text.Encoding = System.Text.Encoding.Unicode
' Convert the string into a byte array.
Dim unicodeBytes As Byte() = unicode.GetBytes(Str)
' Perform the conversion from one encoding to the other.
Dim asciiBytes As Byte() = System.Text.Encoding.Convert(unicode, ascii, unicodeBytes)
' Convert the new byte array into a char array and then into a string.
Dim asciiString As String = ascii.GetString(asciiBytes)
Utf82Hebrew = asciiString
End Function