题目
从标准输入读入一行文本字符,统计并输出其中英文字母、数字字符、空格字符以及其他字符的个数。
输入格式:输入一行包含各种字符的文本字符串(以换行符结束)。
输出格式:分行或按格式输出四类字符的统计数量:letters=数量 digits=数量 spaces=数量 others=数量。
数据范围与约定:字符串长度不超过 1000 字符。
思路与算法
1. 逐字符流式读取
使用 getchar() 循环读取字符,直到遇到 \n 或 输入流结束 为止。
2. 字符分类判断
利用标准库 <ctype.h> 的辅助函数:
英文字母:isalpha(c);
数字:isdigit(c);
空白:isspace(c) 或 c == ' ';
其余字符落入 else 计数。
完整程序
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
if (!sc.hasNextLine()) {
return;
}
String line = sc.nextLine();
int letters = 0;
int digits = 0;
int spaces = 0;
int others = 0;
// 逐字符分类统计
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (Character.isLetter(c)) {
letters++;
} else if (Character.isDigit(c)) {
digits++;
} else if (Character.isWhitespace(c)) {
spaces++;
} else {
others++;
}
}
System.out.println("letters:" + letters);
System.out.println("digits:" + digits);
System.out.println("spaces:" + spaces);
System.out.println("others:" + others);
}
}运行示例
输入:
Hi 2026!输出:
letters:2
digits:4
spaces:1
others:1