.Net(C#)汉字和Unicode编码互相转换

1       if (Regex.IsMatch(values, @"[\u4e00-\u9fa5]"))//判断字符串内是否包含中文字符
2         {
3           values = String2Unicode(values);
4       }
 1 /// <summary>
 2 /// <summary>
 3 /// 字符串转Unicode
 4 /// </summary>
 5 /// <param name="source">源字符串</param>
 6 /// <returns>Unicode编码后的字符串</returns>
 7 public static string String2Unicode(string source)
 8 {
 9     byte[] bytes = Encoding.Unicode.GetBytes(source);
10     StringBuilder stringBuilder = new StringBuilder();
11     for (int i = 0; i < bytes.Length; i += 2)
12     {
13         stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
14     }
15     return stringBuilder.ToString();
16 }
17  
18 /// <summary>
19 /// Unicode转字符串
20 /// </summary>
21 /// <param name="source">经过Unicode编码的字符串</param>
22 /// <returns>正常字符串</returns>
23 public static string Unicode2String(string source)
24 {
25     return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
26                  source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
27 }

 

未完待续

 原文地址:https://www.cnblogs.com/Chareree/p/8714551.html

posted @ 2020-04-14 16:36  小熊爱编程  阅读(918)  评论(1编辑  收藏  举报