从一个字符串中分别获取中文和其他字符的个数

    /**
     * 分别获取一个字符串里面的中文和其他字符所占的字节数
     */
    public static int getLength(String str){
        int strLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /*
         * 获取字符串长度,如果含有中文字符,则每个中文字符占2个字符长度,否则为1
         */
        for (int i = 0; i < str.length(); i++) {
            /*
             * 获取一个字符
             */
            String temp = str.substring(i,i+1);
            if(temp.matches(chinese)){
                /*
                 * 中文字符长度占2个
                 */
                strLength+=2;
            }else{
                /*
                 * 其他字符长度占1个
                 */
                strLength+=1;
            }
        }
        return strLength;
    }
posted @ 2012-09-08 17:12  程序学习笔记  阅读(327)  评论(0编辑  收藏  举报