[代码] [Java]代码
01package service;
02
03
04
05
06import java.util.regex.Matcher;
07
08import java.util.regex.Pattern;
09
10
11
12
13public class CodeChange {
14
15
16
17
18/*
19
20* 把中文字符串转换为十六进制Unicode编码字符串
21
22*/
23
24public static String stringToUnicode(String s) {
25String str = "";
26for (int i = 0; i < s.length(); i++) {
27int ch = (int) s.charAt(i);
28if (ch > 255)
29str += "\\u" + Integer.toHexString(ch);
30else
31str += "\\" + Integer.toHexString(ch);
32}
33return str;
34}
35
36
37
38/*
39
40* 把十六进制Unicode编码字符串转换为中文字符串
41
42*/
43
44public static String unicodeToString(String str) {
45
46Pattern pattern = pile("(\\\\u(\\p{XDigit}{4}))");
47
48Matcher matcher = pattern.matcher(str);
49
50char ch;
51
52while (matcher.find()) {
53
54ch = (char) Integer.parseInt(matcher.group(2), 16);
55
56str = str.replace(matcher.group(1), ch + "");
57
58}
59
60return str;
61
62}
63
64
65
66public static void main(String[] args) {
67
68
69
70// 直接以Unicode字符串的方式初始化字符串时,会自动
71
72String s1 = "\\配\\置\\成\\功\\,\\重\\启\\后\\生\\效";
73
74System.out.println("s1: " + s1);
75
76
77
78//转换汉字为Unicode码
79
80String s2 = "配置成功,重启后生效";
81
82s2 = CodeChange.stringToUnicode(s2);
83
84System.out.println("s2: " + s2);
85
86
87
88//转换Unicode码为汉字
89String 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";
90String s3 = CodeChange.unicodeToString(aaa);
91
92System.out.println("s3: " + s3);
93
94}
95
96
97
98
99}