java 转 unicode_Java String字符串和Unicode字符相互转换代码详解
时间: 2024-03-12 17:44:51 浏览: 77
将Java String字符串转换为Unicode字符:
```java
public static String stringToUnicode(String str) {
StringBuilder unicode = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
unicode.append("\\u").append(Integer.toHexString(c));
}
return unicode.toString();
}
```
将Unicode字符转换为Java String字符串:
```java
public static String unicodeToString(String unicode) {
StringBuilder str = new StringBuilder();
String[] hex = unicode.split("\\\\u");
for (int i = 1; i < hex.length; i++) {
int data = Integer.parseInt(hex[i], 16);
str.append((char) data);
}
return str.toString();
}
```
使用示例:
```java
String str = "hello world";
String unicode = stringToUnicode(str);
System.out.println("Unicode: " + unicode);
String str2 = unicodeToString(unicode);
System.out.println("String: " + str2);
```
输出结果:
```
Unicode: \u0068\u0065\u006c\u006c\u006f\u0020\u0077\u006f\u0072\u006c\u0064
String: hello world
```
阅读全文