码迷,mamicode.com
首页 > 其他好文 > 详细

将Unicode编码转换为汉字字符串

时间:2014-07-27 21:44:30      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

/// <summary>
/// 汉字转换为Unicode编码
/// </summary>
/// <param name="str">要编码的汉字字符串</param>
/// <returns>Unicode编码的的字符串</returns>
public static string ToUnicode(string str)
{
byte[] bts = Encoding.Unicode.GetBytes(str);
string r = "";
for (int i = 0; i < bts.Length; i += 2) r += "\\u" + bts[i + 1].ToString("x").PadLeft(2, ‘0‘) + bts[i].ToString("x").PadLeft(2, ‘0‘);
return r;
}
/// <summary>
/// 将Unicode编码转换为汉字字符串
/// </summary>
/// <param name="str">Unicode编码字符串</param>
/// <returns>汉字字符串</returns>
public static string ToGB2312(string str)
{
string r = "";
MatchCollection mc = Regex.Matches(str, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
byte[] bts = new byte[2];
foreach (Match m in mc)
{
bts[0] = (byte)int.Parse(m.Groups[2].Value, NumberStyles.HexNumber);
bts[1] = (byte)int.Parse(m.Groups[1].Value, NumberStyles.HexNumber);
r += Encoding.Unicode.GetString(bts);
}
return r;
}

将Unicode编码转换为汉字字符串

标签:

原文地址:http://www.cnblogs.com/top15from/p/3871143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!