每日一题 2022.11.7
Java-判断各类型字符个数
描述
输入一行字符串,分别统计出其中英文字母、空格、数字和其它字符的个数
输入描述:
控制台随机输入一串字符串
输出描述:
输出字符串中包含的英文字母个数,数字个数,空格个数,其它字符个数(格式为:英文字母x数字x空格x其他x),预设代码中已给出输出
示例1
输入:
!@#¥% asdyuihj 345678
输出:
英文字母8数字6空格2其他5
备注:
代表数字的ASCII码值为48-57
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder res = new StringBuilder();
int num,cha,spa,oth;
num = cha = spa = oth = 0;
String str = in.nextLine();
for(int i = 0;i < str.length();i++){
char c = str.charAt(i);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')){
cha++;
}else if(c >='0' && c <= '9'){
num++;
}else if(c==' '){
spa++;
}else{
oth++;
}
}
System.out.println("英文字母"+cha+"数字"+num+"空格"+spa+"其他"+oth);
}
}