1.#
点击查看考点
类型转换
点击查看往年相同题目
与 计软智 2022 年补充程序题第 2 题 均考察了字母出现次数.
请补全以下程序, 使其能统计一个语句中各字母出现的次数.
例如, 对于输入:
1C++ is not C with classes
应该输出以下内容:
1a 1
2c 3
3e 1
4h 1
5i 2
6l 1
7n 1
8o 1
9s 4
10t 2
11w 1
1#include <iostream>
2
3using namespace std;
4
5int const text_size = 80;
6
7int main() {
8 char letters[27] = {};
9 char text[text_size] = {};
10 cin.getline(/* (1) */);
11 for (int i = 0; i < strlen(text); ++i) {
12 if (text[i] >= 'a' && text[i] <= 'z') {
13 ++letters[/* (2) */];
14 } else if (/* (3) */) {
15 ++letters[text[i] - 'A' + 1];
16 }
17 }
18 for (int i = 1; i <= 26; ++i) {
19 if (letters[i] != 0) {
20 cout << static_cast<char>(/* (4) */) << '\t'
21 << /* (5) */ << endl;
22 }
23 }
24}
点击查看解答参考
由示例知, 对字母的统计不区分大小写.
text, text_size
text[i] - 'a' + 1
. 由参考代码中的text[i] - 'A' + 1
知, 存在1
偏移.text[i] >= 'A' && text[i] <= 'Z'
i + 'a' - 1
. 由参考代码中的text[i] - 'A' + 1
知, 存在1
偏移.static_cast<int>(letters[i])
. 由于数组元素是char
, 需要转换为int
再输出.