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

C++ 統計字串中英文字母、數字、空格與其他字元個數實作

     編輯:Java 相關知識

題目需求

輸入三行文字,每行最多 80 字符,分別統計大寫字母、小寫字母、數字、空格及其他字符的個數。

完整代碼實現

#include 
using namespace std;

int main() {
    int upper = 0, lower = 0, digit = 0, space = 0, other = 0;
    char text[3][81]; // 80 字符 + '\0'

    for (int i = 0; i < 3; i++) {
        cout << "請輸入第 " << i+1 << " 行:";
        cin.getline(text[i], 81); // 安全讀取整行含空格
    }

    for (int i = 0; i < 3; i++) {
        for (int j = 0; text[i][j] != '\0'; j++) {
            char ch = text[i][j];
            if (ch >= 'A' && ch <= 'Z') upper++;
            else if (ch >= 'a' && ch <= 'z') lower++;
            else if (ch >= '0' && ch <= '9') digit++;
            else if (ch == ' ') space++; // 注意:原代碼誤用 '=',此處修正為 '=='
            else other++;
        }
    }

    cout << "大寫字母個數:" << upper << endl;
    cout << "小寫字母個數:" << lower << endl;
    cout << "數字個數:" << digit << endl;
    cout << "空格個數:" << space << endl;
    cout << "其他字符個數:" << other << endl;
    return 0;
}

關鍵點解析

  • cin.getline:讀取整行包含空格,避免 cin >> 遇空格截斷。
  • 字符分類:利用 ASCII 碼區間判斷,簡單高效。生產代碼建議使用 標準函數 isupper、islower、isdigit、isspace,支援本地化。
  • 邊界處理:陣列大小 81 確保容納 80 字符 + 結束符;迴圈以 '\0' 為終止條件,兼容不足 80 字符的行。
  • 常見錯誤修正:原代碼 else if (ch = ' ') 為賦值而非比較,導致所有非字母數字字符全歸類為空格,此處已修正為 ==。

擴展:使用標準庫算法(C++11+)

#include 
#include 
#include 

void countChars(const string& s, int& u, int& l, int& d, int& sp, int& o) {
    u = count_if(s.begin(), s.end(), [](char c){ return isupper(c); });
    l = count_if(s.begin(), s.end(), [](char c){ return islower(c); });
    d = count_if(s.begin(), s.end(), [](char c){ return isdigit(c); });
    sp = count_if(s.begin(), s.end(), [](char c){ return isspace(c); });
    o = s.length() - u - l - d - sp;
}

總結

字符統計是基礎編程訓練的經典題目。掌握 getline 安全輸入、ASCII 區間判斷或 標準函數、邊界條件處理,能寫出健壯、可移植的 C++ 代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved