Home »
.Net »
C# Programs
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.
C# Basic Programs »