java字符串和unicode互转

直接上代码

private static String decodeUnicode(String input) {
        if (null == input)
            return input;
        int len = input.length();
        StringBuilder output = new StringBuilder(len);
        for (int x = 0; x < len; x++) {
            char ch = input.charAt(x);
            if (ch != '\\') {
                output.append(ch);
            } else {
                x++;
                if (x != len) {
                    ch = input.charAt(x);
                    if (ch == 'u') {
                        if (x + 5 > len) {
                            output.append(input.substring(x - 1));
                            x += 4;
                        } else {
                            String val = input.substring(x + 1, x + 5);
                            try {
                                output.append((char) Integer.parseInt(val, 16));
                            } catch (NumberFormatException e) {
                                output.append(input.substring(x - 1, x + 5));
                            }
                            x += 4;
                        }
                    } else
                        output.append(ch);
                }
            }
        }
        return output.toString();
    }

    private static String encodeUnicode(String input) {
        if (null == input)
            return input;
        int len = input.length();
        StringBuilder output = new StringBuilder(len * 2);
        for (int x = 0; x < len; x++) {
            char ch = input.charAt(x);
            if ((ch < ' ') || (ch > '~')) {
                output.append("\\u");
                String hex = Integer.toHexString(ch);
                for (int i = 0; i < 4 - hex.length(); i++) {
                    output.append('0');
                }
                output.append(hex);
            } else {
                output.append(ch);
            }
        }
        return output.toString();
    }

注意stringbuilder和stringbuffer的区别

stringbuffer线程安全,stringbuilder线程不安全,二者功能完全一样。没有异步情况stringbuilder会快一些。

posted @ 2013-12-09 15:27  带狗狗带  Views(360)  Comments(0Edit  收藏  举报