您的位置:首页 > 编程语言 > Java开发

unicode码 java中文

2014-04-18 11:28 387 查看
最近做项目,要把unicode转为中文,但是本身取出来的时候unicode码已经被转为“\\u6211”了,无法用java默认的转码来转换了。

自己写了一个转换器,根据unicode转码的规律,之后遇到了不少麻烦,例如如果以“\\u”开头但是根本不是unicode码、末尾以“\\”结尾啊什么的。目前是把程序完成为能想到的出错的可能性都覆盖了,以后再碰到再修改。

Java代码








public class UnicodeDecoder {

public static void main(String[] args) {
String s = "\\\u6211\\uadsf\\t\\u7231\u5317\\u4EAC\u5929\\u5B\t89\\\t\u95E8\\\"\\u12";
System.out.println(decode(s));
}

public static String decode(String in) {
try {
return decode(in.toCharArray());
} catch (Exception e) {
e.printStackTrace();
}
return in;
}

private static String decode(char[] in) throws Exception {
int off = 0;
char c;
char[] out = new char[in.length];
int outLen = 0;
while (off < in.length) {
c = in[off++];
if (c == '\\') {
if (in.length > off) { // 是否有下一个字符

c = in[off++]; // 取出下一个字符
} else {
out[outLen++] = '\\'; // 末字符为'\',返回
break;
}
if (c == 'u') { // 如果是"\\u"

int value = 0;
if (in.length > off + 4) { // 判断"\\u"后边是否有四个字符

boolean isUnicode = true;
for (int i = 0; i < 4; i++) { // 遍历四个字符

c = in[off++];
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + c - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + c - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + c - 'A';
break;
default:
isUnicode = false; // 判断是否为unicode码

}
}
if (isUnicode) { // 是unicode码转换为字符

out[outLen++] = (char) value;
} else { // 不是unicode码把"\\uXXXX"填入返回值

off = off - 4;
out[outLen++] = '\\';
out[outLen++] = 'u';
out[outLen++] = in[off++];
}
} else { // 不够四个字符则把"\\u"放入返回结果并继续

out[outLen++] = '\\';
out[outLen++] = 'u';
continue;
}
} else {
switch (c) { // 判断"\\"后边是否接特殊字符,回车,tab一类的

case 't':
c = '\t';
out[outLen++] = c;
break;
case 'r':
c = '\r';
out[outLen++] = c;
break;
case 'n':
c = '\n';
out[outLen++] = c;
break;
case 'f':
c = '\f';
out[outLen++] = c;
break;
default:
out[outLen++] = '\\';
out[outLen++] = c;
break;
}
}
} else {
out[outLen++] = (char) c;
}
}
return new String(out, 0, outLen);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: