首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 統計字串中英文字母、數字、空格與其他字元

     編輯:Java 相關知識

字元分類統計實作教學

輸入一行字串,分別統計英文字母、數字、空格與其他字元的個數。本文提供兩種作法:正則表達式與字元碼判斷。

作法一:正則表達式(簡潔易讀)

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);
    }
}

作法二:ASCII 碼範圍判斷(效能較佳)

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);
    }
}

關鍵 API 對照

方法說明
Character.isLetter(ch)判斷是否為字母(含中文)
Character.isDigit(ch)判斷是否為數字 0-9
Character.isSpaceChar(ch)判斷 Unicode 空白字元

常見錯誤提醒

  • 使用 sc.next() 會在空格處截斷,請改用 sc.nextLine()。
  • 中文字元會被 isLetter() 判定為字母,若需區分中英文需改用 Unicode 區間判斷。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved