• Advertisement
Sign in to follow this  

Getting each character in a string and its frequency

This topic is 4872 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want to search a C++ string for a literal and its number of occurences. Basically, I've created a struct named literal, that has members 'frequency' and 'text'. I want to get every character used in a string (and put each in a vector), and the frequency of each (also put in a vector), and then create a vector of literals that adds these two bits of information. So the string 'Foobar' would give F, o, b, a, and r. And the frequency would be 1, 2, 1, 1, 1. For anyone who's wondering, I'm trying to use the Huffman encoding algorithm to create an encoding format.

Share this post


Link to post
Share on other sites
Advertisement
Here's an interesting C++ way to do this.

#include <map>
#include <string>

using namespace std;

void getFreq(string s, map<char, int> m) {
m.clear();
for (string::iterator i = s.begin(); i != s.end(); ++i) {
++m[*i];
}
}


At the end you will have a map which maps characters to their frequencies.

Share this post


Link to post
Share on other sites
The frequency chart is a one-to-one mapping of the text literal to its frequency. That should suggest the obvious:
std::map<char, size_t> freq_chart;
You can then simply iterate through the string, inserting or incrementing the frequency count into the mapping. Because iterators for std::map return a std::pair of the key and value, it's trivial to print out a frequency table (consider using a std::ostream_iterator, either to cout, a std::stringstream, or some other std::ostream-derived object, such as a std::ofstream).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement