首页 > 解决方案 > 如何计算字母在随机字母字符串中出现的次数

问题描述

我试图找出字母表中每个字母出现在用户创建的随机字符串中的次数。我有所有的代码,减去每次找到一个字符时计算的部分。我曾尝试使用几个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';
     }
      }
}

标签: c++

解决方案


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';

推荐阅读