【考点 · 3级】string 是 C++ 标准库的字符串类,属于 字符串处理 考点,比 C 风格的 char 数组好用一万倍。
【说人话】string 能自动管理内存(不用你算长度、不用手动加 '\0'),还能直接用 + 拼接、用 == 比较、用 << 整体输入输出。易错点:cin >> s 遇到空格就停!要读一整行得用 getline(cin, s)。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s; // 读入字符串
int cnt[26] = {0}; // 统计26个字母的次数,初始化为0
for (int i = 0; i < (int)s.size(); i++) {
cnt[s[i] - 'a']++; // s[i]-'a'把字母映射到0-25的下标
}
for (int i = 0; i < 26; i++) {
if (cnt[i] > 0) {
cout << (char)('a' + i) << ":" << cnt[i] << " ";
}
}
return 0;
}
// 输出: a:5 b:2 c:1 d:1 r:2
getline(cin, s)。如果前面有 cin >> 整数,记得 cin.ignore() 吃掉残留的换行符。s.find(x) != string::npos,别写 >= 0。s.size() 返回的是无符号整数 unsigned,写 i < s.size() 当 s 为空时 i=0 可能死循环。用 i < (int)s.size() 更安全。