字符串与Unicode编码的相互转换

将字符串转换为Unicode编码形式的字符串

private static string ToUnicode(string chineseText)

        {

            if (chineseText.IsNullOrEmpty())

            {

                return string.Empty;

            }

            byte[] btChinese = Encoding.Unicode.GetBytes(chineseText);            

            StringBuilder sbunicode = new StringBuilder();

            for (int i = 0; i < btChinese.Length; i += 2)

            {

                sbunicode.Append(string.Concat("\\u" + btChinese[i + 1].ToString("x").PadLeft(2, '0'), btChinese[i].ToString("x").PadLeft(2, '0')));

            }

            return sbunicode.ToString();

        }

将Unicode形式的字符串转换为正常的字符串

private static string ToGB2312(string unicodeText)

        {

            if (unicodeText.IsNullOrEmpty())

            {

                return string.Empty;

            }

            MatchCollection mcUnicodes= Regex.Matches(unicodeText, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            if (mcUnicodes.Count < 1)

            {

                return string.Empty;

            }

            byte[] bts = new byte[2];

            StringBuilder sbChinese = new StringBuilder(mcUnicodes.Count);           

            foreach (Match mUnicode in mcUnicodes)

            {

                bts[0] = (byte)int.Parse(mUnicode.Groups[2].Value, NumberStyles.HexNumber);

                bts[1] = (byte)int.Parse(mUnicode.Groups[1].Value, NumberStyles.HexNumber);

                sbChinese.Append( Encoding.Unicode.GetString(bts));

            }

            return sbChinese.ToString();

        }

 

你可能感兴趣的:(unicode)