×

C# Tutorial

Basics of .Net

C# Basics

C# Fundamentals

C# Operators

C# Loops

C# Type Conversions

C# Exception Handling

C# String Class

C# Arrays

C# List

C# Stack

C# Queue

C# Collections

C# Character Class

C# Class and Object

C# Namespaces

C# Delegates

C# Constructors

C# Inheritance

C# Operator Overloading

C# Structures

C# File Handling

C# Convert.ToInt32()

C# Int32 (int) Struct

C# DateTime Class

C# Uri Class

C# Database Connectivity

C# Windows

C# Other Topics

C# Q & A

C# Programs

C# Find O/P

C# - Count the Frequency of a Specified Word in a String

Learn, how to count the frequency of the specified word in the given string in C#?
Submitted by Nidhi, on August 17, 2020 [Last updated : March 21, 2023]

Here we will create a program to count the frequency of the specified word in the given string.

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

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.

C# Basic Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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