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

Here, we are going to learn how to find the occurrence of the specified word in a given string in C#?
Submitted by Nidhi, on October 10, 2020

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

Program:

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.






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.