user1579911 user1579911 - 3 months ago 14
C++ Question

C++, count repeated words in the string and display

I have string say "walk talk, can't won't Won't woN'T talk." I want to count the reapeated words and display.
Note: it is not case sensitive.

I have used delimeter

strtok(string, ",.;:\"!? -_\n\t*()@#=+");


and saved it in

char *temp[100];


Now how can I check for repeatation of words? And display as below

3 won't
2 talk
1 can't
1 walk


it should display from highest repeat to lowest. And if the repeatation is same then display alphabetic order.

Sorry for my bad english.

Answer

Use a std::string to hold the result of the strtok(). Then create a std::map<string, int> to hold the count of the times the string (the key) has occurred.

You can populate the map with:

std::map<string, int> myMap;
myMap[tokenizedWord]++; //Increase count of word.

You can then cycle through the map content and print out wherever the integer value is greater than 2.

for (std::map<string, int>::iterator iter = myMap.begin(); iter != myMap.end(); ++iter)
{
    if (iter->second > 1)
        std::cout << "Duplicated word: " << iter->first << " count = " << iter->second;
}

I'll let you figure out how to traverse it in order. You can put the values in a vector or something and use std::sort before printing or whatever else you like. Maps, unfortunately, are associative containers and you can't sort them as it breaks their internal ordering.

Background Info on std::map

A map is an associative array meaning that every key maps to a specific value, and keys are unique. You can actually create a multimap where keys are not unique, so that's why this is important.

Basically, since keys are unique, you can access or create an element just by using the key as the array index.

For example:

//Create a map and insert a couple things into it - prices of meat?
std::map<string, float> myMap;
myMap["Chicken"] = 4.99;
myMap["Turkey"] = 6.99;

//Retrieve the price of something using the key.
std::cout << "Chicken costs " << myMap["Chicken"] << std::end;

You can do standard insertion and location operations on a map too, but the associative array syntax is just simpler, so why bother? :)

PS: To fully answer your comment, just in case, the ++ at the end of myMap[tokenizedWord]++ is just saying to increment the value of the integer value stored for that key by 1. You could just as well do myMap[tokenizedWord] = myMap[tokenizedWord] + 1 OR you could also do myMap[tokenizedWord] += 1.