`
hxy52088
  • 浏览: 9914 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

十六进制Unicode编码字符串与字符串互转

阅读更多
[代码] [Java]代码
view sourceprint?
01 package service; 

02   

03   

04   

05   

06 import java.util.regex.Matcher; 

07   

08 import java.util.regex.Pattern; 

09   

10   

11   

12   

13 public class CodeChange { 

14   

15   

16   

17   

18 /* 

19   

20  *  把中文字符串转换为十六进制Unicode编码字符串 

21   

22  */ 

23   

24     public static String stringToUnicode(String s) { 

25         String str = ""; 

26         for (int i = 0; i < s.length(); i++) { 

27             int ch = (int) s.charAt(i); 

28             if (ch > 255) 

29                 str += "\\u" + Integer.toHexString(ch); 

30             else 

31                 str += "\\" + Integer.toHexString(ch); 

32         } 

33         return str; 

34     } 

35   

36       

37   

38 /* 

39   

40  *  把十六进制Unicode编码字符串转换为中文字符串 

41   

42  */

43   

44     public static String unicodeToString(String str) { 

45   

46         Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");     

47   

48         Matcher matcher = pattern.matcher(str); 

49   

50         char ch; 

51   

52         while (matcher.find()) { 

53   

54             ch = (char) Integer.parseInt(matcher.group(2), 16); 

55   

56             str = str.replace(matcher.group(1), ch + "");     

57   

58         } 

59   

60         return str; 

61   

62     } 

63   

64       

65   

66     public static void main(String[] args) { 

67   

68           

69   

70         // 直接以Unicode字符串的方式初始化字符串时,会自动 

71   

72         String s1 = "\\配\\置\\成\\功\\,\\重\\启\\后\\生\\效"; 

73   

74         System.out.println("s1: " + s1); 

75   

76           

77   

78         //转换汉字为Unicode码 

79   

80         String s2 = "配置成功,重启后生效"; 

81   

82         s2 = CodeChange.stringToUnicode(s2); 

83   

84         System.out.println("s2: " + s2); 

85   

86           

87   

88         //转换Unicode码为汉字 

89 String aaa ="\u4ec0\u4e48\u662f\u5b89\u5168\u63a7\u4ef6\uff1f###\u5b89\u5168\u63a7\u4ef6\u53ef\u4ee5\u4fdd\u8bc1\u7528\u6237\u7684\u5bc6\u7801\u4e0d\u88ab\u7a83\u53d6\uff0c\u4ece\u800c\u4fdd\u8bc1\u8d44\u91d1\u5b89\u5168"; 

90         String s3 = CodeChange.unicodeToString(aaa); 

91   

92         System.out.println("s3: " + s3); 

93   

94     } 

95   

96   

97   

98   

99 }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics