【问题标题】:How to change unicode code to char如何将unicode代码更改为char
【发布时间】:2014-01-18 19:17:49
【问题描述】:

我以这种方式获取 html:

using (var wb = new WebClient())
{
    data = soeArray;
    var response = wb.UploadValues(url, "POST", data);
    string result = System.Text.Encoding.UTF8.GetString(response);
}

但是有像ś这样的unicode代码作为响应。有什么方法可以用来将其更改为相应的字符吗?

【问题讨论】:

    标签: c# unicode utf-8


    【解决方案1】:

    我认为您正在寻找的是System.Web.HttpUtility.HtmlDecode,或者,如果这不是一个网络应用程序,System.Net.WebUtility.HtmlDecode

    例如:

    string result = System.Net.WebUtility.HtmlDecode(System.Text.Encoding.UTF8.GetString(response));
    

    【讨论】:

      【解决方案2】:

      这并不像您想象的那么简单。您返回的代码是十进制 Unicode 代码点。对于这些,您只需将代码转换为十六进制并在它们前面加上 \u 字符。

      int decCode = int.Parse(rawCode.Substring(2));
      string hexCode = decCode.ToString("X");
      char c = Char.Parse("\u" + hexCode);
      

      简单吧? 错误。如果 HTML 中的 Unicode 字符位于带有 ODE 的代码之前(例如 — 表示 \u2014),它们也可以表示为十六进制代码。

      很简单,如果代码前面有'x',我们只需添加逻辑,将其解析为十六进制,对吗?

      rawCode = rawCode.Substring(2);
      if (rawCode[0] == 'x') {
          hexCode = int.Parse(rawCode.Substring(1));
      } else {
          int decCode = int.Parse(rawCode);
          hexCode = decCode.ToString("X");
      }
      char c = Char.Parse("\u" + hexCode);
      

      看起来很简单? 没有。 HTML Unicode 也可以用字符的“EntityName”来表示。 (例如“或©)​​。

      您不想触摸此代码。

      把它留给 HTML 解码器,你需要做的就是这样。

      string s =  System.Net.WebUtility.HtmlDecode("©"); // returns ©
      

      【讨论】:

      • 嘿,即使我将它们放在代码标签中,unicode 代码实际上也会呈现在我的帖子中。
      猜你喜欢
      • 1970-01-01
      • 2013-08-03
      • 2021-12-26
      • 1970-01-01
      • 2019-08-14
      • 2013-02-28
      • 2017-09-23
      • 1970-01-01
      • 2020-03-09
      相关资源
      最近更新 更多