Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 answers

573 users

How to count the occurrences of each word in a string with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string str = "C# (CSharp) is a general-purpose high-level programming language supporting multiple paradigms." +
                     "C# encompasses static typing, strong typing, lexically scoped, imperative, declarative," +
                     "functional, generic, object-oriented (class-based), and component-oriented programming disciplines";
        Dictionary<string, int> wordCount = CountWords(str);

        foreach (var word in wordCount) {
            Console.WriteLine($"{word.Key}: {word.Value}");
        }
    }

    static Dictionary<string, int> CountWords(string input) {
        var wordCount = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
        var words = input.Split(new[] { ' ', '.', ',', '!', '?', ';', ':', '-', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (var word in words) {
            if (wordCount.ContainsKey(word)) {
                wordCount[word]++;
            }
            else {
                wordCount[word] = 1;
            }
        }

        return wordCount;
    }
}

 
 
/*
run:
     
C#: 2
(CSharp): 1
is: 1
a: 1
general: 1
purpose: 1
high: 1
level: 1
programming: 2
language: 1
supporting: 1
multiple: 1
paradigms: 1
encompasses: 1
static: 1
typing: 2
strong: 1
lexically: 1
scoped: 1
imperative: 1
declarative: 1
functional: 1
generic: 1
object: 1
oriented: 2
(class: 1
based): 1
and: 1
component: 1
disciplines: 1
     
*/
 

 



answered Mar 1, 2025 by avibootz

Related questions

...