木子屋 Dnawo's BLOG

C#中文和UNICODE字符转换方法

👤 dnawo 📅 2009-08-03 👁 8165 👍 0 💬 0 🔄 skydream
//中文转为UNICODE字符
string str = "木子屋-http://www.mzwu.com/";
string outStr = "";
string tmp = "";
if (!string.IsNullOrEmpty(str))
{
    for (int i = 0; i < str.Length; i++)
    {
        //将中文字符转为10进制整数,然后转为16进制unicode字符
        tmp = ((ushort)str[i]).ToString("x");
        if (tmp.Length <= 2)
            tmp = "00" + tmp;
        outStr += "\\u" + tmp;
    }
}

//UNICODE字符转为中文
string str = "\\u6728\\u5b50\\u5c4b\\u002d\\u0068\\u0074\\u0074\\u0070\\u003a\\u002f\\u002f\\u0077\\u0077\\u0077\\u002e\\u006d\\u007a\\u0077\\u0075\\u002e\\u0063\\u006f\\u006d\\u002f";
string outStr = "";
if (!string.IsNullOrEmpty(str))
{
    string[] strlist = str.Replace("\\", "").Split('u');
    try
    {
        for (int i = 1; i < strlist.Length; i++)
        {
            //将unicode字符转为10进制整数,然后转为char中文字符
            outStr += (char)ushort.Parse(strlist[i], System.Globalization.NumberStyles.HexNumber);
        }
    }
    catch (FormatException ex)
    {
        outStr = ex.Message;
    }
}

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 FileStream读写文件示例 下一篇 → Effective C# 原则18:实现标准的处理(Dispos…