Unicode与中文互转

在应用开发和数据传输、持久化过程中,中文与 unicode 互转是相当有用的,比如说社交应用中经常用到的传输存储 emoji 表情。整理为工具类后更是方便统一调用,话不多说上源码:

/**
 * <p>unicode 编码解码工具类<p>
 *
 */
public class UnicodeUtil {
 
    /**
     * <p>转为unicode 编码<p>
     * @param string
     * @return unicodeString
     */
    public static String encode(String str) {
        String prifix = "\\u";
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            String code = prifix + format(Integer.toHexString(c));
            unicode.append(code);
        }
        return unicode.toString();
    }
 
    /**
     * <p>unicode 解码<p>
     * @param unicode
     * @return originalString
     */
    public static String decode(String unicode) {
        StringBuffer str = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            int data = Integer.parseInt(hex[i], 16);
            str.append((char) data);
        }
        return str.length() > 0 ? str.toString() : unicode;
    }
    
    /**
     * <p>转为数据库查询编码<p>
     * 向数据库查询时,\\u需要转为%
     * @param str
     * @return
     */
    public static String encodeDBSearchParam(String str) {
        str = encode(str);
        str = str.replace("\\", "%");
        return str;
    }
    
    /**
     * <p>解码数据库查询参数<p>
     * 数据库查询后,回传参数% 转回\\u
     * @param str
     * @return
     */
    public static String decodeDBSearchParam(String str) {
        str = str.replace("%", "\\");
        str = decode(str);
        return str;
    }
    
    /**
     * 为长度不足4位的unicode 值补零
     * @param str
     * @return
     */
    private static String format(String str) {
        for ( int i=0, l=4-str.length(); i<l; i++ ) 
            str = "0" + str;
        return str;
    }
 
}

[原文链接](https://blog.csdn.net/u011704894/article/details/51706519

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,941评论 25 709
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,465评论 2 59
  • 2017-10-9学经汇报: 一、学经日期:2017年10月9日 农历八月二十 晴 星期一 宝贝年...
    b0a4ca4b06a4阅读 3,192评论 0 0