中文与Unicode互转

作者:追风剑情 发布于:2016-7-8 11:28 分类:C#

示例一

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6.  
  7. namespace UnicodeTest
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. string s = "this is a 中文字符串! to unicode.";
  14.  
  15. string ts = CNStringToUnicode(s);
  16. string os = Regex.Unescape(ts);
  17.  
  18. Console.WriteLine("原字符串:"+s);
  19. Console.WriteLine("转换后的字符串:"+ts);
  20. Console.WriteLine("还原字符串:"+os);
  21.  
  22. Console.Read();
  23. }
  24.  
  25. //仅把字符串中的中文转成unicode其它字符保持不变
  26. public static string CNStringToUnicode(string s)
  27. {
  28. string uni_str = "";
  29. for (int l = 0; l < s.Length; l++)
  30. {
  31. int c = s[l];
  32. if (c > 255)
  33. {
  34. uni_str += "\\u" + c.ToString("x").ToUpper();
  35. }
  36. else
  37. {
  38. uni_str += (char)c;
  39. }
  40. }
  41. return uni_str;
  42. }
  43. }
  44. }

运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号