现在的位置: 首页 > 综合 > 正文

Algorithm_String: 正确计算字符串包含的字符个数

2012年07月29日 ⁄ 综合 ⁄ 共 1659字 ⁄ 字号 评论关闭

源码:


public class Demo {

    public static void main(String[] args) {
        String src = "java 苦逼的,程序 猿。";
        // 字符串长度
        System.out.println("src length: " + src.length());
        // 字符串包含的字符个数
        System.out.println("src length constains char: " + fetchCharNumber(src));
        // 字符串包含的字节数
        System.out.println("src constains byte: " + src.getBytes().length);
    }

    /**
     * 计算字符串的长度.
     * 
     * @param src 需要计算的字符串
     * @return -1 表示输入的src是null值
     */
    public static int fetchCharNumber(String src) {
        int counter = -1;
        if (src != null) {
            counter = 0;
            final int len = src.length();
            for (int i = 0; i < len; i++) {
                char sigleItem = src.charAt(i);
                if (isAlphanumeric(sigleItem)) {
                    counter++;
                } else if (Character.isLetter(sigleItem)) {
                    counter = counter + 2;
                } else {
                    counter++;
                }
            }
        } else {
            counter = -1;
        }

        return counter;
    }

    /**
     * 判断字符是否为英文字母或者阿拉伯数字.
     * 
     * @param ch char字符
     * @return true or false
     */
    public static boolean isAlphanumeric(char ch) {
        // 常量定义
        final int DIGITAL_ZERO = 0;
        final int DIGITAL_NINE = 9;
        final char MIN_LOWERCASE = 'a';
        final char MAX_LOWERCASE = 'z';
        final char MIN_UPPERCASE = 'A';
        final char MAX_UPPERCASE = 'Z';

        if ((ch >= DIGITAL_ZERO && ch <= DIGITAL_NINE)
                || (ch >= MIN_LOWERCASE && ch <= MAX_LOWERCASE)
                || (ch >= MIN_UPPERCASE && ch <= MAX_UPPERCASE)) {
            return true;
        } else {
            return false;
        }
    }
}


java 苦逼的,程序 猿。

包含: 4字母(java)+ 1空格 + 3汉字 + 1英文逗号 + 2汉字 + 1空格 + 1汉字 + 1中文句号


String 的 length 属性将汉字与英文、数字、标点、空格等都视为 1 个.

那麽,length = 14 个


java 中中文字符占 2 个char,所有的标点符号以及字母数字、空格等占 1 个char .

那麽,char = 20 个


java 中默认编码中文或者中文标点符号占 3 个字节,英文字母或者标点符号等占 1 个字节。

那麽,byte = 4 x 1 + 1 x 1 + 3 x 3 + 1 x 1 + 2 x 3 + 1 x 1 + 1 x 3 + 1 x 3 =  28 个


打印结果:




注意:

// false
        System.out.println(Character.isLetter(' '));
        // true
        System.out.println(Character.isLetter('a'));
        // true
        System.out.println(Character.isLetter('A'));
        // false
        System.out.println(Character.isLetter('。'));
        // true
        System.out.println(Character.isLetter('我'));
        // false
        System.out.println(Character.isLetter(','));


Character.isLetter 方法,只有是中文或者字母的情况下才会返回 true.








抱歉!评论已关闭.