用到字符串的抓取,与字符串每个元素拿出来比较。
代码主体:
//统计输入字符串的大写字母,小写字母和数字的数量
public static void main(String[] args) {
//定义各自计数的变量
int small = 0, big = 0, num = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("输入字符串");
//将输入的字符串赋给next
String next = scanner.next();
//用循环的方式将字符串中的元素挨个拿出来比较
for (int i = 0; i < next.length(); i++) {
//如果拿出来的元素阿斯克码在这个区间就是小写字母
//注意字符串想拿出单个元素只能用next.charAt(i)来代表该元素
if ((next.charAt(i)) >= 'a' && (next.charAt(i) <= 'z')) {
//计数+1
small++;
}
//如果拿出来的元素阿斯克码在这个区间就是大写字母
else if ((next.charAt(i)) >= 'A' && (next.charAt(i) <= 'Z')) {
//计数+1
big++;
}
//如果拿出来的元素阿斯克码在这个区间就是数字
else if ((next.charAt(i)) >= '0' && (next.charAt(i) <= '9')) {
//计数+1
num++;
}
}
//输出
System.out.println("small = " + small);
System.out.println("big = " + big);
System.out.println("num = " + num);
}
}
输出结果:
输入字符串
sdf12315SDGFS456HJKGBHGhgfftgcfd
small = 12
big = 12
num = 8
Process finished with exit code 0
原文链接: https://blog.csdn.net/daibadetianshi/article/details/136788262