Count the words that matter
A support tool skims ticket text to see which terms keep coming up, ignoring the little joining words.
- Split on whitespace and compare in lowercase.
- Words shorter than three characters are noise and are left out.
- The result maps each remaining word to how many times it appeared.
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.
Where you start
std::map<std::string, int> wordFrequency(std::string text) {
}
Worked examples
| Call | Result |
|---|---|
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;
}