C# Program to Find the Frequency of “the” Word in a String

This is a C# Program to find the frequency of the word ʺtheʺ in a given sentence.

Problem Description

This C# Program Finds the Frequency of the Word ʺtheʺ in a given Sentence.

Problem Solution

Here the frequency of ‘the’ in the given string is found.

Program/Source Code

Here is source code of the C# Program to Find the Frequency of the Word ʺtheʺ in a given Sentence. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

 * C# Program to Find the Frequency of the Word ʺtheʺ in a given Sentence
using System;
class program
    public static void Main()
        string s1;
        Console.WriteLine("Enter the String : ");
        s1 = Console.ReadLine();
        Console.WriteLine(counting.CountStringOccurrences(s1, "the"));
public static class counting
    public static int CountStringOccurrences(string text, string pattern)
        int count = 0;
        int i = 0;
        while ((i = text.IndexOf(pattern, i)) != -1)
            i += pattern.Length;
        return count;
Program Explanation

In this C# program, we are reading the string using ‘s1’ variable. The CountStringOccurrences() function is used to find the frequency of the word “the” in a given sentence from the counting variable. While loop is used to check the IndexOf() function value is not equal to -1.


If the condition is true then execute the statement. Compute the summation of the value of ‘i’ variable with the value of ‘pattern.length’ variable and increment the value of count variable value by 1. Print the frequency of the word “the” in a given sentence.

Runtime Test Cases
Enter the String : 
we only loop once over the source, which reduces the cost of the method.

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.