第一阶段模块三作业第一题

题目:编程统计字符串"ABCD123!@#$%ab"中大写字母、小写字母、数字、其它字符的个数并打印出来。

思路:使用符合规则的正则表达式来和字符串里的每个字符去做对比,符合对应规则则次数加1,最后打印出统计次数即可,具体代码如下。

视频:https://www.bilibili.com/video/BV1tb4y1R7Js/

package com.lagou.homework.part3;
public class CalCount {
    /**
     * 计算待匹配字符串里符合正则表达式的字符个数
     * @param orgStr 待匹配字符串
     * @param regStr 正则表达式
     * @return 次数
     */
    public static int calCount(String orgStr,String regStr){
        char[] charStr = orgStr.toCharArray();
        int count = 0;
        for (char c: charStr){
//            将char类型转换为String类型后去和正则表达式匹配
            if ((c+"").matches(regStr)){
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        String str = "ABCD123!@#$%ab";
//        大写字母正则表达式
        String regBig = "[A-Z]";
//        小写字母正则表达式
        String regSmall = "[a-z]";
//        数字正则表达式
        String regNum = "[0-9]";
//        其它字符正则表达式
        String regSpe = "\\W";
        int count = 0;
        count = calCount(str,regBig);
        System.out.println("字符串" + str + "中的大写字母个数为:" + count);
        count = calCount(str,regSmall);
        System.out.println("字符串" + str + "中的小写字母个数为:" + count);
        count = calCount(str,regNum);
        System.out.println("字符串" + str + "中的数字个数为:" + count);
        count = calCount(str,regSpe);
        System.out.println("字符串" + str + "中其它字符个数为:" + count);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值