Java String strings and Unicode characters convert to each other
- 2020-04-01 03:30:20
- OfStack
After the Java environment is installed, there is a native2ascib. exe in the bin directory of JDK, which can achieve similar functions, but it can also achieve the same functions through Java code.
String conversion unicode Java method snippet:
/**
* String conversion unicode
*/
public static String string2Unicode(String string) {
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
//Fetch each character
char c = string.charAt(i);
//Convert to unicode
unicode.append("\u" + Integer.toHexString(c));
}
return unicode.toString();
}
Unicode conversion string Java method snippet:
/**
* unicode Turn the string
*/
public static String unicode2String(String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\u");
for (int i = 1; i < hex.length; i++) {
//Convert each code point
int data = Integer.parseInt(hex[i], 16);
//Append to string
string.append((char) data);
}
return string.toString();
}
Test Java snippet:
public static void main(String[] args) {
String test = " Most code site address :www.zuidaima.com";
String unicode = string2Unicode(test);
String string = unicode2String(unicode) ;
System.out.println(unicode);
System.out.println(string);
}
Output results:
\ u6700 \ u4ee3 \ u7801 \ u7f51 \ u7ad9 \ u5730 \ u5740 \ u3a \ u77 \ u77 \ u77 \ u2e \ u7a \ u75 \ u69 \ u64 \ u61 \ u69 \ u6d \ u61 \ u2e \ u63 \ u6f \ u6d