【发布时间】:2018-06-24 03:37:46
【问题描述】:
#include <iostream>
#include <string>
using namespace std;
int main () {
int cnt[26] {};
char alpha[26];
string s = "abcdefffggghiii";
for (int i = 0; i < s.length(); i++) {
cnt[s[i] - 'a']++;
}
for (int i = 'a'; i <= 'z'; i++) {
alpha[i - 'a'] = i;
}
for (int i = 0; i < 26; i++) {
if (cnt[i]) {
cout << alpha[i] << " " << cnt[i] << endl;
}
}
return 0;
}
我想按降序打印字符串中每个字母的频率。我曾考虑对 cnt 数组进行排序并从25 打印到0,但它只会打印带有错误字母的频率。如何修复它以降序打印例如 i 3 等等?
【问题讨论】:
-
对
cnt数组进行排序将丢失元素的原始索引,因此您需要以某种方式跟踪它。此外,从字母中减去'a'不能保证为所有字符集提供介于0和25之间的值(它适用于 ASCII 或兼容字符集,但不适用于其他字符集)。