• 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会快一些。

  • 相关阅读:
    Leetcode 191.位1的个数 By Python
    反向传播的推导
    Leetcode 268.缺失数字 By Python
    Leetcode 326.3的幂 By Python
    Leetcode 28.实现strStr() By Python
    Leetcode 7.反转整数 By Python
    Leetcode 125.验证回文串 By Python
    Leetcode 1.两数之和 By Python
    Hdoj 1008.Elevator 题解
    TZOJ 车辆拥挤相互往里走
  • 原文地址:https://www.cnblogs.com/xirtam/p/3465494.html
Copyright © 2020-2023  润新知