Start learning free

LESSON 227 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Word Frequency in C#: Split and Count with a Dictionary

Practice Read the full explanation

Given a string sentence, count how many times each word appears in it. Return a Dictionary where each word of the sentence is a key, and its value is the number of times that word appears.

The words are in lower case and separated by single spaces, and the sentence has at least one word. The order of the entries doesn't matter.

Example 1:

Input: sentence = "the cat and the hat"
Output: {"the": 2, "cat": 1, "and": 1, "hat": 1}
Explanation: "the" appears twice. Every other word appears once.

Example 2:

Input: sentence = "go go go"
Output: {"go": 3}
Explanation: The same word three times gives one key, "go", with the value 3.

Example 3:

Input: sentence = "hello"
Output: {"hello": 1}
Explanation: A sentence of one word: that word appears once.
STEP 1 OF 6
    Ctrl + Enter to check

    C# · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Frequency in C#, explained

    Problem overview

    The method WordFrequency receives a string sentence and returns a Dictionary<string, int> that says how many times each word appears. The words are lowercase and separated by single spaces, and there is at least one word. The order of the entries doesn't matter.

    For "the cat and the hat" the result is the 2, cat 1, and 1, hat 1. For "go go go" it is a single entry, go 3, and for "hello" it is hello 1.

    Approach: split, then count

    There are two jobs. First turn the sentence into separate words. Then count them, using the same pattern as counting letters: a dictionary where each word is a key and the value is its tally.

    The splitting is done by sentence.Split(' '), which cuts the string at every space and returns a string[]. Since the words are separated by single spaces, this gives exactly the words. For "the cat and the hat" the array is the, cat, and, the, hat.

    Counting needs two cases, because a Dictionary throws a KeyNotFoundException when you read a key that isn't there. A word already in the dictionary gets 1 added to its tally. A new word is written with the value 1.

    On the first example, the tallies grow like this: the is new (1), cat is new (1), and is new (1), the is seen again (2) and hat is new (1). The dictionary ends with four entries, and only the has a value above 1.

    Step by step

    1. Split the sentence with Split(' ') into a string[] named words.
    2. Create an empty Dictionary<string, int> named counts. Nothing is counted yet.
    3. Write a foreach loop over words with a string named word.
    4. If counts.ContainsKey(word), add 1 to counts[word].
    5. Otherwise, in an else, set counts[word] to 1.
    6. Return counts after the loop.

    The solution in C#

    class Solution {
        public Dictionary<string, int> WordFrequency(string sentence) {
            string[] words = sentence.Split(' ');
            Dictionary<string, int> counts = new Dictionary<string, int>();
            foreach (string word in words) {
                if (counts.ContainsKey(word)) {
                    counts[word] += 1;
                } else {
                    counts[word] = 1;
                }
            }
            return counts;
        }
    }

    Details worth knowing:

    • Split(' ') takes a char, written with single quotes. It cuts at each single space. A sentence with no space gives an array with one item, the whole string, which is why "hello" works.
    • The separator is a single character, so two spaces in a row would produce an empty string between them, and that empty string would be counted as a word. For "a b" the array has 3 items. The lesson promises single spaces, so this doesn't come up here.
    • Comparison of keys is case-sensitive, so "The" and "the" would be different keys. The lesson's words are all lowercase.

    Complexity

    Splitting and the loop both go through the sentence once, and each dictionary operation takes constant time on average, so the time is O(n) for a sentence of n characters. The array and the dictionary together take O(n) space.

    Edge cases and common mistakes

    • Reading a missing key. counts[word] += 1 without the ContainsKey check throws on the first word.
    • Splitting on the wrong thing. Split(',') or a forgotten Split would leave the whole sentence as one key.
    • A repeated word. "go go go" gives one key with the value 3, not three keys.
    • One word. A sentence of one word gives a single entry with the value 1.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free