C#
string manipulation
word frequency
text analysis
programming tips

Find the highest occuring words in a string C

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

In C#, finding the highest occurring words within a string is a common task that can be efficiently handled using collections and LINQ. This article delves into the technical aspects of solving this problem using C# programming, complete with code examples and explanations. By the end of this article, you'll be equipped to implement a solution that identifies the most frequently occurring words in any given string.

Parsing the String

Splitting the String

The first step in identifying the highest occurring words is to parse the string into individual words. This can be achieved using the Split method. In typical scenarios, words are separated by spaces, but we also need to consider other delimiters such as punctuation marks. Here's a simple example:

csharp
string text = "Hello world! Hello universe. Hello everyone.";
char[] delimiters = new char[] { ' ', '!', '.', '?' };
string[] words = text.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

Explanation

  • We use an array of characters including a space, exclamation mark, period, and question mark as delimiters.
  • StringSplitOptions.RemoveEmptyEntries removes any empty entries from the resulting array.

Counting Word Occurrences

Using a Dictionary

After parsing the words, we need a way to count occurrences. For this purpose, a Dictionary<string, int> can be particularly useful. Here's how you can use it:

csharp
1Dictionary<string, int> wordCount = new Dictionary<string, int>();
2
3foreach (string word in words)
4{
5    string lowerWord = word.ToLower();
6    if (wordCount.ContainsKey(lowerWord))
7    {
8        wordCount[lowerWord]++;
9    }
10    else
11    {
12        wordCount[lowerWord] = 1;
13    }
14}

Explanation

  • The words are converted to lowercase to ensure case insensitivity.
  • If the word is already in the dictionary, its count is incremented.
  • If not, the word is added with an initial count of 1.

Finding the Highest Occurring Words

Utilizing LINQ

Once we have a dictionary of word counts, LINQ can be employed to find the words with the highest frequency. Consider the following code snippet:

csharp
1int maxCount = wordCount.Values.Max();
2var mostFrequentWords = wordCount
3    .Where(pair => pair.Value == maxCount)
4    .Select(pair => pair.Key);

Explanation

  • Values.Max() retrieves the maximum count from the dictionary.
  • We filter (Where) those entries whose value matches the maximum count.
  • Finally, we select only the keys (words) corresponding to these entries.

Full Example

Here’s the complete code that combines all the above pieces:

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5class Program
6{
7    static void Main()
8    {
9        string text = "Hello world! Hello universe. Hello everyone.";
10        char[] delimiters = new char[] { ' ', '!', '.', '?' };
11        string[] words = text.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
12
13        Dictionary<string, int> wordCount = new Dictionary<string, int>();
14
15        foreach (string word in words)
16        {
17            string lowerWord = word.ToLower();
18            if (wordCount.ContainsKey(lowerWord))
19            {
20                wordCount[lowerWord]++;
21            }
22            else
23            {
24                wordCount[lowerWord] = 1;
25            }
26        }
27
28        int maxCount = wordCount.Values.Max();
29        var mostFrequentWords = wordCount
30            .Where(pair => pair.Value == maxCount)
31            .Select(pair => pair.Key);
32
33        Console.WriteLine($"Most frequent words: {string.Join(", ", mostFrequentWords)} (Count: {maxCount})");
34    }
35}

Summary Table

The table below summarizes the key steps involved in finding the highest occurring words in a string:

StepDescription
Parse the StringSplit the string into words using delimiters.
Count OccurrencesUse a dictionary to count the frequency of each word, converting words to lowercase for case insensitivity.
Find Maximum CountUse LINQ to determine the maximum word count.
Identify WordsFilter and select words that have the maximum count.

Conclusion

Finding the highest occurring words in a string involves parsing, counting, and filtering processes. By leveraging C# collections and LINQ, we can effectively and efficiently determine word frequencies and identify the most frequent words. This technique can be particularly useful in text analysis, data processing, and natural language processing applications.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.