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