需求:輸入一行字串,統計每個英文字母出現次數,輸出最高頻字元
解題思路
- 建立長度 26 的整數陣列
count[26] = {0},對應 a-z。
- 逐字元讀取輸入,若為字母(
isalpha),轉小寫(tolower),對應索引計數器遞增。
- 遍歷陣列找出最大值及其索引,輸出字元與次數。
參考代碼
#include <iostream>
#include <cctype>
using namespace std;
int main() {
int count[26] = {0};
char ch;
while ((ch = cin.get()) != '\n' && ch != EOF) {
if (isalpha(ch)) {
count[tolower(ch) - 'a']++;
}
}
int maxIdx = 0;
for (int i = 1; i < 26; ++i) {
if (count[i] > count[maxIdx]) maxIdx = i;
}
cout << "最高頻字元: " << char('a' + maxIdx) << " 次數: " << count[maxIdx] << endl;
// 可選:輸出所有字元統計
for (int i = 0; i < 26; ++i) {
if (count[i]) cout << char('a'+i) << ": " << count[i] << endl;
}
return 0;
}
擴展建議
- 若需統計所有 ASCII 字元,擴大陣列至 128 或 256。
- 使用
std::map<char, int> 或 std::unordered_map 處理 Unicode 或動態字元集。
- 大數據量時考慮多執行緒 MapReduce。