經典字符串處理:讀多行輸入(每行長度 ≤ 100,000),統計每行中 a-z 出現次數,按格式 字母:次數 輸出,每行結束輸出空行。
getline(含空格、標點)cnt 歸零isalpha(c) 判斷字母,轉小寫 tolower(c),cnt[c-'a']++a:cnt[0] 到 z:cnt[25],每項換行#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string line;
while (getline(cin, line)) {
array cnt{}; // C++11 聚合初始化為 0
for (char ch : line) {
if (isalpha(static_cast(ch))) {
cnt[tolower(static_cast(ch)) - 'a']++;
}
}
for (int i = 0; i < 26; ++i) {
cout << char('a' + i) << ':' << cnt[i] << '\n';
}
cout << '\n';
}
return 0;
}
| 點 | 處理 |
|---|---|
| 輸入結束 | while(getline(cin,line)) 自動處理 EOF |
| 大小寫 | tolower 統一轉小寫 |
| 非字母 | isalpha 過濾,需轉 unsigned char 避免負值 UB |
| 輸出格式 | 每項獨立行,測試用例間空行 |
| 性能 | O(行長),array 避免動態分配,ios::sync_with_stdio(false) 加速 IO |
輸入: hello, this is my first acm contest! work hard for hdu acm. 輸出: a:1 b:0 c:2 ... z:0 a:2 b:0 c:1 ... z:0
此題是字符統計、流處理、格式輸出的基礎綜合訓練,適合 ACM 入門練習。