【问题标题】:Mixed Encoding to String混合编码到字符串
【发布时间】:2012-08-02 21:25:56
【问题描述】:

我在 VB.net 中有一个字符串,它可能包含以下内容:

这是一个 0x000020AC 符号

根据本文http://www.fileformat.info/info/unicode/char/20ac/index.htm,这是欧元符号的UTF-32编码

我想把它转换成

这是一个€符号

我尝试在 VB.net 中使用 UnicodeEncoding() 类(Framework 2.0,因为我正在修改旧版应用程序)

当我使用这个类编码,然后解码时,我仍然得到原始字符串。

我希望 UnicodeEncoding 能够识别已经编码的部分,而不是对其进行编码。但似乎并非如此。

对于如何将混合编码字符串转换为普通字符串,我现在有点迷茫。

背景:将 Excel 电子表格保存为 CSV 时,ascii 范围之外的任何内容都会转换为 ?。所以我的想法是,如果我能让我的客户搜索/替换一些字符,比如欧元符号,变成一个编码字符串,比如 0x000020AC。然后我希望在插入 SQL 数据库之前将这些编码部分转换回真实的符号。

我试过这样的功能

Public Function Decode(ByVal s As String) As String
    Dim uni As New UnicodeEncoding()
    Dim encodedBytes As Byte() = uni.GetBytes(s)
    Dim output As String = ""

    output = uni.GetString(encodedBytes)

    Return output
End Function

这是基于 MSDN http://msdn.microsoft.com/en-us/library/system.text.unicodeencoding.aspx 上的示例

这可能是我完全误解了它在 VB.net 中的工作原理。在 C# 中,我可以简单地使用转义字符,例如“\u20AC”。但在 VB.net 中不存在这样的东西。

【问题讨论】:

标签: vb.net encoding decoding


【解决方案1】:

根据 Heinzi 的建议,我使用以下代码实现了 Regex.Replace 方法,这似乎适用于我的示例。

Public Function Decode(ByVal s As String) As String
 Dim output As String = ""
 Dim sRegex As String = "0x[0-9a-zA-Z]{8}"

 Dim r As Regex = New Regex(sRegex)

 Dim myEvaluator As MatchEvaluator = New MatchEvaluator(AddressOf HexToString)

 output = r.Replace(s, myEvaluator)

 Return output
End Function

Public Function HexToString(ByVal hexString As Match) As String
 Dim uni As New UnicodeEncoding(True, True)
 Dim input As String = hexString.ToString
 input = input.Substring(2)
 input = input.TrimStart("0"c)

 Dim output As String

 Dim length As Integer = input.Length
 Dim upperBound As Integer = length \ 2
 If length Mod 2 = 0 Then
  upperBound -= 1
 Else
  input = "0" & input
 End If
 Dim bytes(upperBound) As Byte
 For i As Integer = 0 To upperBound
  bytes(i) = Convert.ToByte(input.Substring(i * 2, 2), 16)
 Next

 output = uni.GetString(bytes)

 Return output
End Function

【讨论】:

    【解决方案2】:

    你试过了吗:

    Public Function Decode(Byval Coded as string) as string
         Return StrConv(Coded, vbUnicode)
    End Function
    

    另外,您的功能无效。它将 s 作为参数,执行大量内容,然后输出放入其中的 s,而不是其中处理的内容。

    【讨论】:

    • 我在问题中看到了那个错误,对此感到抱歉。在发布之前,我尝试了该脚本的许多版本。无论如何,不​​幸的是 vbUnicode 在 .net 中被删除并且仅适用于 VB6。所以这对我不起作用。
    • System.Text.Encoding.Convert 将字符串转换为字节数组怎么样? msdn.microsoft.com/en-us/library/…
    • 我设法使用 Heinzi 之前的评论找到了一种方法。使用正则表达式和自定义匹配评估器,结合 hextostring 函数。整理一下代码我会自己贴出来分享一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多