c++ - 如何计算字母在随机字母字符串中出现的次数
问题描述
我试图找出字母表中每个字母出现在用户创建的随机字符串中的次数。我有所有的代码,减去每次找到一个字符时计算的部分。我曾尝试使用几个for...else
循环来解决这个问题,但也许我只是没有学会正确地做到这一点,我总是在输出的其余部分下出现错误或空白。
我想要的是输出看起来像这样:
A B C D E F G...
1 2 5 7 0 9 2...
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <map>
using namespace std;
int main() {
int i=0, n;
char alphabet[26];
char c;
char RandomStringArray [100];
srand(time(0));
cout <<"How many letters do you want in your random string (no less than 0, no more than 100): ";
cin >> n;
for (int i=0; i<=25; i++)
alphabet[i] = 'a' + i;
while(i<n) {
int temp = rand() % 26;
RandomStringArray[i] = alphabet[temp];
i++;
}
for(i=0; i<n; i++)
cout<<RandomStringArray[i];
cout<<"\n\n";
/*for(c = 'A'; c <= 'Z'; ++c)
cout<<" "<<c;
cout<<"\n";
*/
map<char,size_t> char_counts;
for (int i = 0; i < n; ++i) ++char_counts[RandomStringArray[i]];{
for (char ch :: alphabet) std::cout << ch << ' ';{
std::cout << '\n';
}
for (char ch :: alphabet) std::cout << char_counts[ch] <<'';{
std::cout << '\n';
}
}
}
解决方案
std::unordered_map
对这种事情有好处。它类似于为每个字符保存计数的数组方法,但使用起来更方便,尤其是当您感兴趣的字符范围不连续时。
当您索引 a 时std::unordered_map
,映射值将通过引用返回,因此您只需递增它。如果它不存在,则创建它并默认初始化(整数类型初始化为零)。
所以你需要做的就是:
std::unordered_map<char, std::size_t> char_counts;
for (int i = 0; i < n; ++i) ++char_counts[RandomStringArray[i]];
在此之后,char_counts
保存字符串中所有字符的总出现次数。egchar_counts['a']
是 的出现次数'a'
。
然后将它们全部打印出来,您可以执行以下操作:
for (char ch : alphabet) std::cout << ch << ' ';
std::cout << '\n';
for (char ch : alphabet) std::cout << char_counts[ch] << ' ';
std::cout << '\n';
推荐阅读
- html - getUserMedia - 图像大小
- excel - Excel VBA NOW() 粘贴到不被识别为日期/时间的单元格中
- spring - 在 SpringBoot 2 中最小化方法注入参数
- oracle - CLOB 列的 FOR UPDATE 中的 ORA-25006
- java - 向 weblogic 上托管的 webservice 提交 post xml 请求,并从客户端请求中获取响应 xml
- typescript - firebase 交易,您必须返回一个承诺
- asp.net - 在内容页visual basic asp.net中设置母版页标签文本时出现空引用异常
- sparql - Wikidata SPARQL 从别名查询中提取排名项目
- spring-data-jpa - Junit 测试用例失败 400 错误请求
- python - 如何使用 Python 访问我的 Firefox 配置文件中的页面