Q:

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

belongs to collection: C# Basic Programs | String programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | String programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to trim a specified string... >>
<< How to replace a character with another character ...