PackageService;ImportJava.util.regex.Matcher;ImportJava.util.regex.Pattern; Public classCodechange {/** Convert Chinese string to hexadecimal Unicode encoded string*/ Public Staticstring Stringtounicode (String s) {string str= ""; for(inti = 0; I < s.length (); i++) { intCH = (int) S.charat (i); if(Ch > 255) Str+ = "\\u" +integer.tohexstring (CH); ElseStr+= "\\" +integer.tohexstring (CH); } returnstr; } /** Convert hexadecimal Unicode encoded string to Chinese string*/ Public Staticstring unicodetostring (String str) {pattern pattern= Pattern.compile ("(\\\\u (\\p{xdigit}{4})")); Matcher Matcher=Pattern.matcher (str); Charch; while(Matcher.find ()) {ch= (Char) Integer.parseint (Matcher.group (2), 16); STR= Str.replace (Matcher.group (1), CH + ""); } returnstr; }
Public Static voidMain (string[] args) {//when a string is initialized directly as a Unicode string, it is automaticallyString S1= "\ \ test \ \ \ \ \ \\! "; System.out.println ("S1:" +S1); //convert Chinese characters to Unicode codeString S2= "Test Data"; S2=codechange.stringtounicode (S2); System.out.println ("S2:" +S2); //convert Unicode codes to Chinese charactersString AAA = "\u4ec0\u4e48"; String S3=codechange.unicodetostring (AAA); System.out.println ("S3:" +S3); }}
Java 16 binary, Unicode mutual transfer