JavaSE中你想看的例子——统计字符串中数字、汉字、字母....各个的总数

编写一个方法,

①用来统计所给字符串中大写英文字母的个数,

②小写英文字母的个数,

③数字的个数 ,

④汉字的个数(汉字的范围:[\u4e00-\u9fa5])

⑤以及其他字符的个数

public class Test03 {
    public static void main(String[] args) {
        String string = "sd23jk33我是34你好";
        String hanZi = "[\u4e00-\u9fa5]";//判断这个字符是否为汉字
        String shuZi = "[0-9]";//判断这个字符是否为数字
        String bigWord = "[A-Z]";//判断这个字符是否为大写字母
        String smallWord = "[a-z]";//判断这个字符是否为小写字母
        int hanZi_count = 0;//记录匹配到的汉字个数
        int shuZi_count = 0;//记录匹配到的数字个数
        int bigWord_count = 0;//记录匹配到的大写字母个数
        int smallWord_count = 0;//记录匹配到的小写字母个数
        int otherWord_count = 0;//记录匹配到的其他字符个数
        for (int i = 0; i < string.length(); i++) {
            String string2 = string.substring(i, i+1);
            if (string2.matches(hanZi)) {//判断这个字符是否为汉字
                hanZi_count++;
            }else if (string2.matches(shuZi)) {//判断这个字符是否为数字
                shuZi_count++;
            }else if (string2.matches(bigWord)) {//判断这个字符是否为大写字母
                bigWord_count++;
            }else if (string2.matches(smallWord)) {
                smallWord_count++;
            }else{
                otherWord_count++;
            }
        }
        System.out.println("汉字有:" + hanZi_count);
        System.out.println("数字有:" + shuZi_count);
        System.out.println("大写字母有:" + bigWord_count);
        System.out.println("小写字母有:" + smallWord_count);
        System.out.println("其他字符有:" + otherWord_count);   
    }
}

 

posted @ 2017-05-06 17:44  Java_皮卡丘漏电  阅读(452)  评论(0编辑  收藏  举报