Zethos
Zethos

Reputation: 71

How to count the number of times a letter shows up in a randomized string of alphabetical letters

I am trying to find the number of times each letter of the alphabet shows up in a randomized string that the user creates. I have all the code, minus the portion that would count each time a character is found. I have tried to use a couple of for...else loops to figure this out, but maybe I am just not learned to do it correctly, I keep either getting errors or a blank space under the rest of the output.

What I want is for the output to look like this:

A B C D E F G... 1 2 5 7 0 9 2...

Here is my code and my output so far: enter image description here enter image description here

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

Upvotes: 2

Views: 425

Answers (1)

Cruz Jean
Cruz Jean

Reputation: 2819

std::unordered_map is good for this sort of thing. It's similar to the array approach of holding counts for each character but is more convenient to use, especially when the character ranges you're interested in are non-contiguous.

When you index a std::unordered_map the mapped value will be returned by reference, so you just increment it. If it doesn't exist it's created and default initialized (zero initialized for integer types).

So all you need to do is:

std::unordered_map<char, std::size_t> char_counts;
for (int i = 0; i < n; ++i) ++char_counts[RandomStringArray[i]];

After this, char_counts holds the total occurrence counts for all characters in the string. e.g. char_counts['a'] is the number of occurrences of 'a'.

Then to print them all out you could do:

for (char ch : alphabet) std::cout << ch << ' ';
std::cout << '\n';

for (char ch : alphabet) std::cout << char_counts[ch] << ' ';
std::cout << '\n';

Upvotes: 1

Related Questions