1. 程式人生 > >如何獲取含有中文字元的字串長度

如何獲取含有中文字元的字串長度

當字串含有中文字元,計算字串長度用傳統方法會有問題。如:

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;
    }
這是計算含有中文字元的字串長度的兩種方法,希望對大家有所幫助。