程序开发 > C# > 正文

C# Unicode转字符串与字符串转换Unicode(含中文)

亮术网 2020-08-10 本网原创

编写涉及到文字处理的程序,将Unicode转字符串或都把字符串转换Unicode编码,是经常要写的代码。如果要区别中英文,还要用到中文Unicode编码范围和英文Unicode编码范围。

字符串转换Unicode 容易实现一些,Unicode转字符串稍微复杂一点,需要转为十六进制,再转为二进制比特流,最后才转字符串,下面将列出它们转换的实现代码。

 

一、Unicode转字符串

以下方法可以处理带 0x 的和不带 0x 的 Unicode 字符串,不过要统计,不能有些带 0x 有些不带,要么全带要么全不带。

using System.Globalization;

/// <summary>
  /// C# Unicode转字符串
  /// </summary>
  /// <param name="text">Unicode</param>
  /// <returns>字符串</returns>

  public string UnicodeToString(string text)
  {
    if (string.IsNullOrEmpty(text)) return null;

  string temp = null;
    bool flag = false;

  int len = text.Length / 4;
    if (text.StartsWith("0x") || text.StartsWith("0X"))
    {
      len = text.Length / 6;//Unicode字符串中有0x
      flag = true;
    }

  StringBuilder sb = new StringBuilder(len);
    for (int i = 0; i < len; i++)
    {
      if (flag)
        temp = text.Substring(i * 6, 6).Substring(2);
      else
        temp = text.Substring(i * 4, 4);

    byte[] bytes = new byte[2];
      bytes[1] = byte.Parse(int.Parse(temp.Substring(0, 2), NumberStyles.HexNumber).ToString());
      bytes[0] = byte.Parse(int.Parse(temp.Substring(2, 2), NumberStyles.HexNumber).ToString());
      sb.Append(Encoding.Unicode.GetString(bytes));
    }
    return sb.ToString();
  }

调用方法:

string strUni="0x00200x4e2d0x65870x5b570x7b260x4e320x8f6c0x63620x00550x006e0x0069
0x00630x006f0x00640x0065"
;

或者 string strUni = "00204e2d65875b577b264e328f6c63620055006e00690063006f00640065";

UnicodeToString(strUni)

输出结果:中文字符串转换Unicode

 

 

二、字符串转换Unicode

/// <summary>
  /// C# 字符串转换Unicode
  /// </summary>
  /// <param name="text">字符串</param>
  /// <returns>Unicode编码</returns>

  public string StringToUnicode(string text)
  {
    bool flag = false;
    string strUni = null;
    string temp = null;

  foreach (char c in text)
    {
      temp = string.Format("{0:x}", (int)c);

    if (temp.Length < 3)
        temp = "00" + temp;

    if (flag)
        strUni += ",0x" + temp;
      else
        strUni += "0x" + temp;

    if (!flag)
        flag = true;
    }
    return strUni;
  }

string str = "C# 中文字符串转换Unicode";

StringToUnicode(str);

 

输出 Unicode编码:

0x0043,0x0023,0x0020,0x4e2d,0x6587,0x5b57,0x7b26,0x4e32,0x8f6c,0x6362,0x0055,0x006e,
0x0069,0x0063,0x006f,0x0064,0x0065

 

中文字符转Unicode 直接把要转换字符调用上述方法,就可以得到相应的 Unicode 编码。