java 將字串中的中文encode
阿新 • • 發佈:2019-01-03
遍歷字串中的所有字元,判斷是否為中文,如果是中文進行轉碼,如果不是就繼續
/** * 將字串中的中文進行編碼 * @param s * @return 返回字串中漢字編碼後的字串 */ private String cnToEncode(String s ){ char[] ch = s.toCharArray(); String result = ""; for(int i=0;i<ch.length;i++){ char temp = ch[i]; if(isChinese(temp)){ try { String encode = URLEncoder.encode(String.valueOf(temp), "utf-8"); result = result + encode; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ result = result+temp; } } return result; }
/** * 判斷字元是否為漢字 * @param c * @return */ private static boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) { return true; } return false; }
呼叫:
s = cnToEncode(s);