Android针对两种UNICODE转中文

来源:互联网 发布:如何做网站推广优化 编辑:程序博客网 时间:2024/06/05 15:12

首先,这是我在项目中遇到的两种unicode格式,
第一种较为常见,第二种是首次遇到,

// 磷叶石.–<宝石之国>
String unicode = “\u78f7\u53f6\u77f3”;
String unicode2 = “磷叶石”;

如果是第一种的话,可采用以下这种方式解码:

 public static String decode(String unicodeStr) {        if (unicodeStr == null) {            return null;        }        StringBuffer retBuf = new StringBuffer();        int maxLoop = unicodeStr.length();        for (int i = 0; i < maxLoop; i++) {            if (unicodeStr.charAt(i) == '\\') {                if ((i < maxLoop - 5) && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr.charAt(i + 1) == 'U')))                    try {                        retBuf.append((char) Integer.parseInt(unicodeStr.substring(i + 2, i + 6), 16));                        i += 5;                    } catch (NumberFormatException localNumberFormatException) {                        retBuf.append(unicodeStr.charAt(i));                    }                else                    retBuf.append(unicodeStr.charAt(i));            } else {                retBuf.append(unicodeStr.charAt(i));            }        }        return retBuf.toString();    }

(原文地址:http://blog.csdn.net/zimo2013/article/details/40780439)
第二种的话,

public static String decode2(String unicodeStr) {        if (unicodeStr == null) {            return null;        }        StringBuffer stringBuffer = new StringBuffer();        int maxLoop = unicodeStr.length();        for (int i = 0; i < maxLoop; i++) {            if (unicodeStr.charAt(i) == '&' && unicodeStr.charAt(i + 1) == '#') {                int endNode = -1; // 结束节点.                for (int j = i + 2; j < i + 10; j++) {                    if (unicodeStr.charAt(j) == ';') {                        endNode = j;                        break;                    }                }                if (endNode != -1) {                    char c = (char) Integer.parseInt(unicodeStr.substring(i + 2, endNode), 10);                    stringBuffer.append(c);                    i = endNode;                }            }        }        return stringBuffer.toString();    }

总结,仔细观察可发现,两种的区别无非是16进制vs10进制,原理相同,一通百通.
原理就是这两句了:

char c = (char) Integer.parseInt(unicodeStr.substring(i + 2, i + 6), 16)
char c = (char) Integer.parseInt(unicodeStr.substring(i + 2, endNode), 10);

unicode编码,根据进制parse为int,再强转为char即为对应的字符.