Learn C# · lesson 37 of 61 · about 11 minutes
Project: Word Counter
Listen in at the tavern: read everything people say about the battle, count the words, and find the most common ones.
What you'll learn
- Clean text before counting
- Count with a dictionary or GroupBy
- Report the top results
Tales at the tavern
That night, everyone at the tavern tells the tale of the battle, and the bard wants to know which words come up most. Everything left in the input is read at once with Console.In.ReadToEnd(), made lower case, and split on spaces, new lines and punctuation with RemoveEmptyEntries, so Dragon! and dragon are the same word. Then the totals, the longest word with MaxBy, and the top three with GroupBy, OrderByDescending and ThenBy, which puts tied words in alphabetical order. If nobody says anything, there are no tales tonight.
The plan
1. Read all the input with Console.In.ReadToEnd()
2. Make it lower case and split on spaces, new lines and punctuation
3. Count each word with GroupBy
4. Print the totals and the top three
The counter
string text = Console.In.ReadToEnd().ToLower();
char[] separators = { ' ', '\n', '\r', '.', ',', '!', '?' };
string[] words = text.Split(separators, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine($"Words: {words.Length}, different: {words.Distinct().Count()}");
Console.WriteLine($"Longest: {words.MaxBy(w => w.Length)}");
var top = words.GroupBy(w => w)
.OrderByDescending(g => g.Count())
.ThenBy(g => g.Key)
.Take(3);
foreach (var g in top) Console.WriteLine($"{g.Key,-8}{g.Count()}");Output
Words: 10, different: 5
Longest: penguin
the 3
penguin 2
saw 2Tip
ThenBy breaks ties: words with the same count are sorted alphabetically. MaxBy returns the item with the largest key, not the key itself.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.