天天看點

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

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

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;
    }           

這是計算含有中文字元的字元串長度的兩種方法,希望對大家有所幫助。