题目
读入一行文本,统计字母、数字、空格与其他字符
思路
用 Scanner.nextLine() 读一行,Character.isLetter/isDigit/isWhitespace 分类,其余计入 others。
解题分析
不必使用 C 的 Character 类;标点等既非字母数字又非空白时归入 others。
完整程序
import java.io.*;
public class Main {
public static void main(String[] args) {
String s = "Hi 2026!";
int letters = 0, digits = 0, spaces = 0, others = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isLetter(ch)) letters++;
else if (Character.isDigit(ch)) digits++;
else if (Character.isWhitespace(ch)) spaces++;
else others++;
}
System.out.println("letters:" + letters);
System.out.println("digits:" + digits);
System.out.println("spaces:" + spaces);
System.out.println("others:" + others);
}
}
运行示例
输出:
letters:2
digits:4
spaces:1
others:1