题目:编程统计字符串"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);
}
}