當字符串含有中文字符,計算字符串長度用傳統方法會有問題。如:
String s="a啊A";System.out.PRintln("the length of s:"+s.length());輸出為3。實際上這樣輸出是不對的,因為一個中文字符長度大于1。可用按如下方法進行計算://字符串含有中文求字節數:String temp="aa啊啊A";System.out.println("temp長度:"+temp.getBytes(Charset.defaultCharset()).length);輸出為9。或者按下面這種方式進行計算:
//計算文件名長度public static int checkNameLength(String filename){ int len = 0; if (filename == null || filename.isEmpty()) { return 0; } try { len = filename.getBytes(UTF_8).length; } catch (UnsupportedEncodingException e) { if(LogUtil.isErrorLogEnable()){ LogUtil.e(TAG, "UnsupportedEncodingException", e); } len = filename.length(); } return len; }這是計算含有中文字符的字符串長度的兩種方法,希望對大家有所幫助。
新聞熱點
疑難解答