Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Monday 7 September 2020

Program to find the occurrence of the character in a string in C#

In some interviews or exams, a problem is provided to the interviewee or student to find out the occurrence of the character in a string. In this example, I will help you in solving that problem/program with the easiest approach.

Program to find the occurrence of the character in a string
Let’s follow the process shown in the below image. As C# in the case-sensitive language, I am converting the string to the lowercase string so that I can compare the characters otherwise capital character and small alphabetical character will be treated as different characters.
Program to find the occurrence of the character in a string in C# is provided below:

string Statement = "";

Console.WriteLine("Enter a string to find number of Occurrence of a character");

Statement = Console.ReadLine();

//Converting the Statement to lowercase which help in counting of the character in the string

//As C# is Case-Sensitive

Statement = Statement.ToLower();

//Check the length of string entered by the user

if (Statement.Length>0) {

//Iterate till length of statement is greater than zero

//Here we check each character occurrence

//Once count is checked, we will remove that character from the string

while (Statement.Length > 0)

{

    //CountCharacter to store the character occurrence

    int CountCharacter = 0;

    Console.Write("Number of Occurance of '"+Statement[0] + "': ");

    //Checking the Character occurrence in the string entered by the user

    for (int i=0;i<Statement.Length;i++)

    {

        if (Statement[0]==Statement[i])

        {

            CountCharacter++;

        }

    }

    //Displaying the Count of each character

    Console.Write(CountCharacter+"\n");

    //Removing that character from the string

    Statement = Statement.Replace(Statement[0].ToString(), string.Empty);

}

}

//Console.ReadLine() to hold the screen after the execution of the program

Console.ReadLine();

Output:

I hope this example will help in your interview/exam preparation.
Thanks

0 comments:

Post a Comment

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook

Blog Archive