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

 1         /// <summary>
 2         /// 将Unicode编码转换为汉字字符串
 3         /// </summary>
 4         /// <param name="str">Unicode编码字符串</param>
 5         /// <returns>汉字字符串</returns>
 6         public static string ToGB2312(string str)
 7         {
 8             StringBuilder sb = new StringBuilder();
 9             MatchCollection mCollection2 = Regex.Matches(str, "([\w]+)|(\\u([\w]{4}))");
10             if (mCollection2 != null && mCollection2.Count > 0)
11             { 
12                 foreach (Match m2 in mCollection2)
13                 {
14                     string v = m2.Value;
15                     if (v.StartsWith("\u"))
16                     {
17                         string word = v.Substring(2);
18                         byte[] codes = new byte[2];
19                         int code = System.Convert.ToInt32(word.Substring(0, 2), 16);
20                         int code2 = System.Convert.ToInt32(word.Substring(2), 16);
21                         codes[0] = (byte)code2;
22                         codes[1] = (byte)code;
23                         sb.Append(Encoding.Unicode.GetString(codes));
24                     }
25                     else
26                     {
27                         sb.Append(v);
28                     }
29                 } 
30             }
31             return sb.ToString();
32         }

 1         //可以包括其他字符       
 2         public string uncode(string str)
 3         {
 4             string outStr = "";
 5             Regex reg = new Regex(@"(?i)//u([0-9a-f]{4})");
 6             outStr = reg.Replace(str, delegate(Match m1)
 7             {
 8                 return ((char)Convert.ToInt32(m1.Groups[1].Value, 16)).ToString();
 9             });
10             return outStr;
11         }
原文地址:https://www.cnblogs.com/tomsense/p/3939794.html