Drill

ProblemsC++ › text

Count the words that matter

mediumtextHash mapsStringsParsingC++

A support tool skims ticket text to see which terms keep coming up, ignoring the little joining words.

wordFrequency(text: string) → map<string, int>

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

std::map<std::string, int> wordFrequency(std::string text) {
    
}

Worked examples

CallResult
wordFrequency(std::string("card declined card"))std::map<std::string, int>{{std::string("card"), 2}, {std::string("declined"), 1}}
wordFrequency(std::string("The the THE"))std::map<std::string, int>{{std::string("the"), 3}}
wordFrequency(std::string("a an I ok"))std::map<std::string, int>{}
wordFrequency(std::string(""))std::map<std::string, int>{}

Hint

Lowercase before counting, or "Payment" and "payment" end up as two entries.

Reference solution in C++
std::map<std::string, int> wordFrequency(std::string text) {
    std::map<string, int> result;
    string lower;
    for (char c : text) lower += static_cast<char>(tolower(static_cast<unsigned char>(c)));
    istringstream in(lower);
    string w;
    while (in >> w) {
        if (w.size() < 3) continue;
        result[w]++;
    }
    return result;
}

The same problem in another language

More text problems in C++