C# - Count the Frequency of a Specified Word in a String

Learn, how to count the frequency of the specified word in the given string in C#?
Submitted by Nidhi, on August 17, 2020 [Last updated : March 21, 2023]

Here we will create a program to count the frequency of the specified word in the given string.

C# program to count the frequency of the specified word in the given string

The source code to print the count of the word in the specified string in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to count the frequency of the 
//specified word in the given string.

using System;

class WordFrequency
{
    public static int CountWordFrequncy(string sentence, string word)
    {
        int cnt = 0;
        int i = 0;
        while ((i = sentence.IndexOf(word, i)) != -1)
        {
            i += word.Length;
            cnt++;
        }
        return cnt;
    }
    public static void Main()
    {
        string sentence;

        Console.Write("Enter the Sentence: ");
        sentence = Console.ReadLine();

        Console.WriteLine(CountWordFrequncy(sentence, "the"));
    }
}

Output

Enter the Sentence: India is the great country, the india is very cultural country
2
Press any key to continue . . .

Explanation

In the above program, we created a WordFrequency class that contains two static methods CountWordFrequency() and Main(). The CountWordFrequency() method returns the count of the specified word in the specified string. In the Main() method we created a string variable and took sentence as an input and then find the word occurrence and print on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.