Counting words in a string programming exercise.

Its like this. When the government counts the populous they sometime count the the same people two or more times. Or was it during the elections… Anyway, your job is to:

Write a function that takes an array of strings and counts the number of each unique element(words) present. The result shout be in form of a:

Dictionary<string, int>
Example: apple, hello, apple, Olivia, Emma, Emma, Emma
output: apple 2, hello 1, Olivia 1, Emma 3

Scroll down for the solution of this coding problem for beginners.

If you don’t already know, the dictionary is a very special form of a two dimensional array, with special functionality that can be used only with it.

        Dictionary<string,int> dict = new Dictionary<string, int>();
        dict.Add("Emma",3);
        Console.WriteLine(dict["Emma"]);

The first variable of the two in a dictionary is called key. It can be used to call the second variable, called value. The key is used to call the corresponding value like this:

dict["Emma"]

This will return the second variable, called “value”. You cannot use the value to call the key. Because the value is not necessary unique. Emma my occur 3 times, but Ben can also occur 3 times. Only the key have to be unique – so it can call the value.

The plan for the solution is as follows:

I am going to use some functions to get only the unique elements form the original list, then go through each one of them, and count how many times they occur. Then I will save each string and the number of its occurrences in the dictionary.

1) I will start by declaring the dictionary.
2) The first function is Distinct(). This is a function in the Linq library, that will return us only the unique elements from an array. In form of an IEnumerable<>. And since this will be even more complicated for our example, we need use ToArray() so that we can get a nice simple string array.
3) Now lets go through every string in the array with the unique strings.
Then go through every string in the original array and compare both items.
If they match, we count that.
4) Now we save the string and the number of its occurrences.
5) And finally we return the result.

    public static Dictionary<string, int> Count(string[] words)
    {
        //Step 1
        Dictionary<string, int> r = new Dictionary<string, int>();
        //Step 2
        string[] uniques = words.Distinct().ToArray();
        //Step 3
        foreach (var word in uniques)
        {
            int counter = 0;
            foreach (var item in words)
            {
                if (word == item) counter++;
            }
        //Step 4
            r.Add(word, counter);
        }
        //Step 5
        return r;
    }