輸入一行字串,分別統計英文字母、數字、空格與其他字元的個數。本文提供兩種作法:正則表達式與字元碼判斷。
import java.util.Scanner;
public class CharStatRegex {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入字串:");
String str = sc.nextLine(); // 讀取整行含空格
int letter = 0, digit = 0, space = 0, other = 0;
for (char ch : str.toCharArray()) {
if (Character.isLetter(ch)) letter++;
else if (Character.isDigit(ch)) digit++;
else if (Character.isSpaceChar(ch) || ch == ' ') space++;
else other++;
}
System.out.printf("英文字母:%d%n數字:%d%n空格:%d%n其他:%d%n", letter, digit, space, other);
}
}
public class CharStatAscii {
public static void main(String[] args) {
String str = "Hello World 123!@#";
int letter = 0, digit = 0, space = 0, other = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) letter++;
else if (c >= '0' && c <= '9') digit++;
else if (c == ' ' || c == '\t' || c == '\n') space++;
else other++;
}
System.out.println("字母:" + letter + " 數字:" + digit + " 空格:" + space + " 其他:" + other);
}
}
| 方法 | 說明 |
|---|---|
Character.isLetter(ch) | 判斷是否為字母(含中文) |
Character.isDigit(ch) | 判斷是否為數字 0-9 |
Character.isSpaceChar(ch) | 判斷 Unicode 空白字元 |
sc.next() 會在空格處截斷,請改用 sc.nextLine()。isLetter() 判定為字母,若需區分中英文需改用 Unicode 區間判斷。