2018-11-16 中文 和Unicode 互转

** 中文 和Unicode编码互转**
1.符合客户端方式转换

/// 
    /// 字符串转Unicode码
    /// 
    /// The to unicode.
    /// Value.
    private string StringToUnicode(string value)
    {
        byte[] bytes = Encoding.Unicode.GetBytes(value);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < bytes.Length; i += 2)
        {
            // 取两个字符,每个字符都是右对齐。
            stringBuilder.AppendFormat("u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
        }
        return stringBuilder.ToString();
    }

    /// 
    /// Unicode转字符串
    /// 
    /// The to string.
    /// Unicode.
    private string UnicodeToString(string unicode)
    {
        string resultStr = "";
        string[] strList = unicode.Split('u');
        for (int i = 1; i < strList.Length; i++)
        {
            resultStr += (char)int.Parse(strList[i], System.Globalization.NumberStyles.HexNumber);
        }
        return resultStr;
    }

2.符合js规则的转换

 /// 
    /// unicode转中文(符合js规则的)
    /// 
    /// 
    public static string unicode_js_1(string str)
    {
        string outStr = "";
        Regex reg = new Regex(@"(?i)%u([0-9a-f]{4})");
        outStr = reg.Replace(str, delegate (Match m1)
        {
            return ((char)Convert.ToInt32(m1.Groups[1].Value, 16)).ToString();
        });
        return outStr;
    }

    /// 
    /// 中文转unicode(符合js规则的)
    /// 
    /// 
    public static string unicode_js_0(string str)
    {
        string outStr = "";
        string a = "";
        if (!string.IsNullOrEmpty(str))
        {
            for (int i = 0; i < str.Length; i++)
            {
                if (Regex.IsMatch(str[i].ToString(), @"[\u4e00-\u9fa5]"))
                { outStr += @"%u" + ((int)str[i]).ToString("x"); }
                else { outStr += str[i]; }
            }
        }
        return outStr;
    }

你可能感兴趣的:(2018-11-16 中文 和Unicode 互转)