Q:

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

belongs to collection: C# Basic Programs | String programs

0

C# program to find the occurrence of the specified word in a 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 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.

 

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 convert a string from lowercase to u... >>
<< C# program to replace a substring within a specifi...