java对含有中文的字符串进行Unicode编码


public class MyUtil {
    public static void main(String[] args) throws Exception {
        String s = "a中aabb";
        String url = setUrlForChn(s);
        System.out.println(url);
    }
    
    /**
     * 对含有中文的字符串进行Unicode编码
     * \ue400 \u9fa5 Unicode表中的汉字的头和尾
     */
    public static String setUrlForChn(String url) throws Exception{
        String regEx = "[\u4e00-\u9fa5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(url);
        StringBuffer sb = new StringBuffer();
        while(m.find()){
            m.appendReplacement(sb, URLEncoder.encode(m.group(), "UTF-8"));
        }
        m.appendTail(sb);
        return sb.toString();
    }
}

打印:

a%E4%B8%ADaabb


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM