概述
项目需要Unicode编码与字符串互转,在此做个笔录。
1、code
// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,
// then press Enter. You can now see whitespace characters in your code.
public class Main {
public static void main(String[] args) {
// Press Alt+Enter with your caret at the highlighted text to see how
// IntelliJ IDEA suggests fixing it.
System.out.println("Hello and welcome!");
String strArray[] = {"嘿嘿嘿hahaha001122", "123456789"};
for (int i = 0; i < strArray.length; i++) {
System.out.println("***************** stringToUnicode *****************");
String unicode = stringToUnicode(strArray[i]);
System.out.println("stringToUnicode:" + unicode);
System.out.println("***************** unicodeToString *****************");
String uniStr = unicodeToString(unicode);
System.out.println("unicodeToString:" + uniStr + "\n");
}
}
public static String unicodeToString(String unicode) {
StringBuffer string = new StringBuffer();
/* 以 \ u切割 */
String[] hex = unicode.split("\\\\u");
for (int i = 1; i < hex.length; i++) {
/* 这里代表将值转为16进制表示,一共有2, 8, 10, 16几种表示 */
int data = Integer.parseInt(hex[i], 16);
/* 追加成String */
string.append((char) data);
}
return string.toString();
}
public static String stringToUnicode(String string) {
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
/* 取出每一个字符 */
char c = string.charAt(i);
/* 转换为unicode Integer.toHexString(); 返回字符的16进制表示 */
unicode.append("\\u" + Integer.toHexString(c));
}
return unicode.toString();
}
}
2、运行结果
3、总结
希望能帮助到需要的攻城狮,谢谢观阅!!!