【问题标题】:How to decode a Unicode character in a string如何解码字符串中的 Unicode 字符
【发布时间】:2012-02-15 23:32:59
【问题描述】:

如何在 C# 中解码此字符串 'Sch\u00f6nen' (@"Sch\u00f6nen"),我尝试了 HttpUtility 但它没有给我所需的结果,即“Schönen”。

【问题讨论】:

  • 你看过 System.Text.Encoding 类吗?您也许可以使用UTF-8 编码来解码 Unicode 字符串内容

标签: c#


【解决方案1】:

Regex.Unescape 成功了:

System.Text.RegularExpressions.Regex.Unescape(@"Sch\u00f6nen");

请注意,在测试变体或编写单元测试时需要小心:"Sch\u00f6nen" 已经是 "Schönen"。您需要在字符串前面加上@ 才能将\u00f6 视为字符串的一部分。

【讨论】:

  • 我知道这条评论已经过时了,但你已经解决了我关于在 unicode 之前添加 @ 的评论的问题。非常感谢。
【解决方案2】:

如果您因为看到"Sch\u00f6nen"(或字符串常量中的类似\uXXXX 值)而遇到此问题,则它不是编码。这是一种将 Unicode 字符表示为转义序列的方法,类似于 \n 表示新行和 \r 表示返回的字符串。

我认为您不必解码。

string unicodestring = "Sch\u00f6nen";
Console.WriteLine(unicodestring);

Schönen 被输出。

【讨论】:

  • 好吧,当我在 Windows Phone 模拟器上输出它时,它显示为“Sch\u00f6nen”,因此需要对其进行转义。回答我的问题后删除帖子的用户得到了正确答案,我不知道他为什么删除它。
  • 我认为你们两个互相误解了:) @findcaiyzh,如果你用string unicodestring = "Sch\\u00f6nen"; 更新你的例子,你会得到@M_K 正在谈论的情况。这种情况在处理从远程端点检索的 JSON 结果时很常见。
【解决方案3】:

编写了将 unicode 字符串转换为实际字符的代码。 (但本主题中的最佳答案工作正常且不那么复杂)。

string stringWithUnicodeSymbols = @"{""id"": 10440119, ""photo"": 10945418, ""first_name"": ""\u0415\u0432\u0433\u0435\u043d\u0438\u0439""}";
var splitted = Regex.Split(stringWithUnicodeSymbols, @"\\u([a-fA-F\d]{4})");
string outString = "";
foreach (var s in splitted)
{
    try
    {
        if (s.Length == 4)
        {
            var decoded = ((char) Convert.ToUInt16(s, 16)).ToString();
            outString += decoded;
        }
        else
        {
            outString += s;
        }
    }
    catch (Exception e)
    {
        outString += s;
    }
}

【讨论】:

  • 使用length==4 检查,很确定这可能会给\uAAAAAAA\uAAAA 之类的在unicode 字符之间长度为4 个字符串的东西提供错误的结果。不过,核心转换足以编写解析器。
猜你喜欢
  • 2017-11-23
  • 1970-01-01
  • 2017-07-14
  • 2019-12-10
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
相关资源
最近更新 更多