How to count the frequency of words in a string?

Sep 9, 2014 at 7:37am
What is the best way to count the frequency of words in a string?

Sample Input:
I don't know the key to success but key failure is trying please everybody.

Sample Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Word          Frequency
I                1
don't            1
know             1
the              2
key              1
to               3
success          1
but              1
key              1
failure          1
is               1
trying           1
please           1
everybody        1 


Someone write the code for me please..
Sep 9, 2014 at 7:52am
Someone write the code for me please


No.

Create a map of <std::string, int> (your string and your frequency).
iterate over the your string. for each word you come across search your map for it.
1. If the string can not be found in your map, add it to you map and a set the frequency to one.
2. If the string can be found increment the corresponding frequency by one.
Sep 9, 2014 at 3:56pm
actually I am so beginner that I don't understand <map>.
can you be more specific please?
Last edited on Sep 9, 2014 at 3:57pm
Sep 9, 2014 at 5:28pm
Did you look at the example program in:
http://www.cplusplus.com/reference/map/map/find/

Too bad, it makes assumptions (for simplicity). It has these lines:
1
2
std::cout << "a => " << mymap.find('a')->second << '\n';
std::cout << "c => " << mymap.find('c')->second << '\n';

They would crash, if the map doesn't have 'a' or 'c'.
They are safer like this:
1
2
3
4
5
6
7
8
auto it = mymap.find('a');
if ( mymap.end() != it ) {
  std::cout << "a => " << it->second << '\n';
}
it = mymap.find('c');
if ( mymap.end() != it ) {
  std::cout << "c => " << it->second << '\n';
}

Naturally, when a key is not found, it has to be added: http://www.cplusplus.com/reference/map/map/emplace/

It is somewhat of a leap to get into standard library, but it is worth the effort.

Topic archived. No new replies allowed.