苏飞论坛

标题: asp.net C#把Unicode编码转换为汉字,支持非Unicode编码字符串混合 [打印本页]

作者: Monn    时间: 2013-9-29 01:01
标题: asp.net C#把Unicode编码转换为汉字,支持非Unicode编码字符串混合
本帖最后由 Monn 于 2013-9-29 10:27 编辑

从网上找的Unicode编码转换为汉字方法都是只能转换Unicode编码的字符串,但是有时会需要用到Unicode编码的汉字和其他字符串混用,所以才有了如下方法,很简单不多说了,直接看代码吧。。


[code=csharp]/// <summary>  
/// 将Unicode编码转换为汉字,支持英文数字等字符串和Unicode编码字符串混合  
/// </summary>  
/// <param name="str">含有Unicode编码字符串</param>  
/// <returns>汉字字符串</returns>  
public string UniToGB(string str)  
{  
    string StrGb = "";  
    int i = 0;  
    MatchCollection mc = Regex.Matches(str, @"[url=file://\\u([\w]{2})([\w]{2]\\u([\w]{2})([\w]{2[/url]})", RegexOptions.Compiled | RegexOptions.IgnoreCase);  
    byte[] bts = new byte[2];  
    if (mc.Count != 0)  
    {  
        foreach (Match m in mc)  
        {  
            bts[0] = (byte)int.Parse(m.Groups[2].Value, System.Globalization.NumberStyles.HexNumber);  
            bts[1] = (byte)int.Parse(m.Groups[1].Value, System.Globalization.NumberStyles.HexNumber);  
            string r = Encoding.Unicode.GetString(bts);//Unicode转为汉字  
            i++;  
            if (i == 1)  
            {  
                StrGb = str.Replace(m.Groups[0].Value, r);  
            }  
            else
            {  
                StrGb = StrGb.Replace(m.Groups[0].Value, r);  
            }  
        }  
        return StrGb;  
    }  
    else
    {  
        return str;  
    }  
}[/code]





欢迎光临 苏飞论坛 (http://www.sufeinet.com/) Powered by Discuz! X3.4