當字符串含有中文字符,計算字符串長度用傳統方法會有問題。如:
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;
}
這是計算含有中文字符的字符串長度的兩種方法,希望對大家有所幫助。