java实现unicode编码与解码的程序
时间: 2024-05-14 22:15:08 浏览: 48
以下是Java实现Unicode编码与解码的程序:
Unicode编码:
```java
public static String unicodeEncode(String str) {
StringBuilder sb = new StringBuilder();
char[] charArray = str.toCharArray();
for (char c : charArray) {
sb.append("\\u").append(Integer.toHexString(c));
}
return sb.toString();
}
```
Unicode解码:
```java
public static String unicodeDecode(String str) {
StringBuilder sb = new StringBuilder();
String[] hexArray = str.split("\\\\u");
for (int i = 1; i < hexArray.length; i++) {
int hexValue = Integer.parseInt(hexArray[i], 16);
sb.append((char) hexValue);
}
return sb.toString();
}
```
示例:
```java
String str = "Hello, 世界!";
String encodedStr = unicodeEncode(str);
System.out.println(encodedStr); // \u0048\u0065\u006c\u006c\u006f\u002c\u0020\u4e16\u754c\u0021
String decodedStr = unicodeDecode(encodedStr);
System.out.println(decodedStr); // Hello, 世界!
```
阅读全文