C# - Count Occurrences of a Word in String

Given a string, we have to count occurrences of a specified word in the given string using C# program?
Submitted by Nidhi, on October 10, 2020 [Last updated : March 21, 2023]

Here, we read a string from the keyboard and then find the occurrence of a specified word in a specified string.

C# program to count occurrences of a word in string

The source code to find the occurrence of a specified word in a given string is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to find the occurrence of the 
//specified word in a given string.

using System;

class Demo
{
    static int FindOccurrence(string str, string word)
    {
        int count = 0;
        int len = 0;

        while(true)
        {
            len = str.IndexOf(word, len);
            if(len<0)
                break;
            len += word.Length;
            count++;
        }
        
        return count;
    }
    static void Main()
    {
        string str="";
        string word="are";
        int count = 0;

        Console.WriteLine("Enter the String : ");
        str = Console.ReadLine();

        count = FindOccurrence(str, "are");

        Console.WriteLine("Occurrences of the word [{0}] are: {1}",word,count);
    }
}

Output

Enter the String :
There are two fans in a room and there are two rooms in a flat
Occurrences of the word [are] are: 2 
Press any key to continue . . .

Explanation

Here, we created a Demo class that contains two static methods FindOccurrence() and  Main() method.

The FindOccurrence() word is used to count the occurrence of a specified word in a specified string.

The Main() method is the entry point of the program. Here we created a string initialized with a sentence, here we read a string and then find the occurrence of a specified word and printed the count on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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