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

public Dictionary<string, int> WordFrequency(string text) {
    
}

Worked examples

CallResult
WordFrequency("card declined card")new Dictionary<string, int> { { "card", 2 }, { "declined", 1 } }
WordFrequency("The the THE")new Dictionary<string, int> { { "the", 3 } }
WordFrequency("a an I ok")new Dictionary<string, int> { }
WordFrequency("")new Dictionary<string, int> { }

Hint

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

Reference solution in C#
public Dictionary<string, int> WordFrequency(string text) {
    var result = new Dictionary<string, int>();
    foreach (var w in text.ToLowerInvariant().Split((char[]) null, StringSplitOptions.RemoveEmptyEntries)) {
        if (w.Length < 3) continue;
        result[w] = result.ContainsKey(w) ? result[w] + 1 : 1;
    }
    return result;
}

The same problem in another language

More text problems in C#