How to create an ASCII frequency table from a string in C++

1 Answer

0 votes
#include <array>
#include <iostream>
#include <unordered_map>

std::unordered_map<char, int> getASCIIFrequency(const std::string& str) {
    std::array<int, 128> frequencyTable = {0};

    for (char c : str) {
        frequencyTable[static_cast<int>(c)]++;
    }

    std::unordered_map<char, int> result;
    for (int i = 0; i < frequencyTable.size(); i++) {
        if (frequencyTable[i] > 0) {
            result[static_cast<char>(i)] = frequencyTable[i];
        }
    }

    return result;
}

int main() {
    std::string str = "c++ c c++ c# java python php";
    auto asciiFrequency = getASCIIFrequency(str);

    for (const auto& pair : asciiFrequency) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
}



/*
run:

v: 1
t: 1
o: 1
j: 1
h: 2
p: 3
c: 4
y: 1
+: 4
#: 1
n: 1
a: 2
 : 6

*/

 



answered Oct 17, 2024 by avibootz

Related questions

1 answer 112 views
1 answer 114 views
1 answer 120 views
1 answer 133 views
1 answer 115 views
1 answer 107 views
...