C#
Public
Count Words with Dictionary
Count repeated words with a Dictionary in a simple console example.
#csharp
#dictionary
#string
#count
C#
using System;
using System.Collections.Generic;
string text = "csharp is useful and csharp is fun";
string[] words = text.ToLower().Split(' ');
Dictionary<string, int> counts = new();
foreach (string word in words)
{
if (!counts.ContainsKey(word))
{
counts[word] = 0;
}
counts[word]++;
}
foreach (var item in counts)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
Notes
Dictionary is a good fit when you need key-value counts.