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

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

     編輯:Java 相關知識

字元分類統計實作

常見需求:讀取一行輸入,分別統計英文字母、數字、空白字元、中文字(漢字)與其他符號的出現次數。本文提供完整的 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);
    }
}

關鍵點解析

  • nextLine() vs next():next() 遇空白截斷,必須用 nextLine() 讀取完整行。
  • Character 工具類:isLetter()、isDigit()、isSpaceChar() 簡化判斷邏輯。
  • Unicode 範圍:中文常用漢字區間 \u4e00-\u9fa5,可擴充至擴展區。
  • 效能:單次遍歷 O(n),記憶體 O(1)。

擴充建議

  • 使用正則表達式 Pattern.compile("[a-zA-Z]") 等進行批次比對。
  • 統計結果以 Map<String, Integer> 回傳,利於後續處理。
  • 支援補充字元(Supplementary Characters)需用 codePointAt 遍歷。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved