常見需求:讀取一行輸入,分別統計英文字母、數字、空白字元、中文字(漢字)與其他符號的出現次數。本文提供完整的 Scanner 讀取整行(含空白)並逐字元判斷的範例。
import java.util.Scanner;
public class CharCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("請輸入字串:");
String input = scanner.nextLine(); // 讀取整行,保留空白
int letters = 0, digits = 0, spaces = 0, chinese = 0, others = 0;
for (char ch : input.toCharArray()) {
if (Character.isLetter(ch)) {
// 進一步區分英文與中文
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
letters++;
} else if (ch >= '\u4e00' && ch <= '\u9fa5') {
chinese++;
} else {
// 其他語系字母歸類為 others 或自行擴充
others++;
}
} else if (Character.isDigit(ch)) {
digits++;
} else if (Character.isSpaceChar(ch) || ch == ' ') {
spaces++;
} else {
others++;
}
}
System.out.println("英文字母:" + letters);
System.out.println("中文字數:" + chinese);
System.out.println("數字個數:" + digits);
System.out.println("空格個數:" + spaces);
System.out.println("其他字元:" + others);
}
}
next() 遇空白截斷,必須用 nextLine() 讀取完整行。isLetter()、isDigit()、isSpaceChar() 簡化判斷邏輯。\u4e00-\u9fa5,可擴充至擴展區。O(n),記憶體 O(1)。Pattern.compile("[a-zA-Z]") 等進行批次比對。Map<String, Integer> 回傳,利於後續處理。codePointAt 遍歷。