华为机试题-统计字符
HJ40 统计字符
知识点:字符串
描述
输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数。
本题包含多组输入。
数据范围:输入的字符串长度满足
输入描述:
输入一行字符串,可以有空格
输出描述:
统计其中英文字符,空格字符,数字字符,其他字符的个数
示例1
输入:1qazxsw23 edcvfr45tgbn hy67uj m,ki89ol.\/;p0-=\][
输出: 26
3
10
12
知识点:
比较简单,直接上代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String str = sc.nextLine();
int letters = 0;
int digits = 0;
int spaces = 0;
int others = 0;
int len = str.length();
for(int i = 0; i < len; i++) {
char ch = str.charAt(i);
if(Character.isLetter(ch)) { // isLetters(char ch)用来判断输入内容是否是字母
letters++;
} else if(Character.isDigit(ch)) {
digits++;
} else if(Character.isSpace(ch)) {
spaces++;
} else {
others++;
}
}
System.out.println(letters);
System.out.println(spaces);
System.out.println(digits);
System.out.println(others);
}
}
}
浙公网安备 33010602011771号