java统计字符个数

public class StringHomework03 {
    public static void main(String[] args) {
        try {
            String s = statisticChar1("123abcABC");
            // 数字个数: 3, 大写字母个数: 3, 小写字母个数: 3
            System.out.println(s);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        try {
            String s2 = statisticChar2("ABCabc123");
            // 数字个数: 3, 大写字母个数: 3, 小写字母个数: 3
            System.out.println(s2);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public static String statisticChar1(String str) {
        if (str == null) {
            throw new RuntimeException("字符串不能为空");
        }

        int numberCount = 0;
        int BigCount = 0;
        int smallCount = 0;

        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] >= '0' && chars[i] <= '9') {
                numberCount++;
            } else if (chars[i] >= 'A' && chars[i] <= 'Z') {
                BigCount++;
            } else if (chars[i] >= 'a' && chars[i] <= 'z') {
                smallCount++;
            }
        }

        return "数字个数: " + numberCount + ", 大写字母个数: " + BigCount + ", 小写字母个数: " + smallCount;
    }

    public static String statisticChar2(String str) {
        if (str == null) {
            throw new RuntimeException("字符串不能为空");
        }

        int numberCount = 0;
        int BigCount = 0;
        int smallCount = 0;

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c >= '0' && c <= '9') {
                numberCount++;
            } else if (c >= 'A' && c <= 'Z') {
                BigCount++;
            } else if (c >= 'a' && c <= 'z') {
                smallCount++;
            }
        }

        return "数字个数: " + numberCount + ", 大写字母个数: " + BigCount + ", 小写字母个数: " + smallCount;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值