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

Here, we are going to learn how to count the frequency of the specified word in the given string in C#?
Submitted by Nidhi, on August 17, 2020

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

Program:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.