首页 > Windows开发 > 详细

C# Unicode编码解码

时间:2019-10-26 15:21:50      阅读:86      评论:0      收藏:0      [点我收藏+]

public static class CommpnHelpEx
{
/// <summary>
/// unicode编码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ToUnicodeString(this string str)
{
StringBuilder strResult = new StringBuilder();
if (!string.IsNullOrEmpty(str))
{
for (int i = 0; i < str.Length; i++)
{
strResult.Append("\\u");
strResult.Append(((int)str[i]).ToString("x"));
}
}
return strResult.ToString();
}


/// <summary>
/// unicode解码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string FromUnicodeString(this string str)
{
//最直接的方法Regex.Unescape(str);
StringBuilder strResult = new StringBuilder();
if (!string.IsNullOrEmpty(str))
{
string[] strlist = str.Replace("\\", "").Split(‘u‘);
try
{
for (int i = 1; i < strlist.Length; i++)
{
int charCode = Convert.ToInt32(strlist[i], 16);
strResult.Append((char)charCode);
}
}
catch (FormatException ex)
{
return Regex.Unescape(str);
}
}
return strResult.ToString();
}
}

 

 

 

使用方式:

 string str = "我是共.产.党";
            string unicodeStr = str.ToUnicodeString();

            string chStr = unicodeStr.FromUnicodeString();

C# Unicode编码解码

原文:https://www.cnblogs.com/dinggf/p/11743199.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!