Count occurrences of a character within String in C#

Hi Programmers, welcome to new article of c#.net. This article i’ll write the program to Find the Number of Occurrences of a Character in a String in C# Console application. To Achieve the output we should use for loop ( any loop you can use) and if or if else statement.
Let’s see the codes.

Directly Test Below Codes into Editor.

using System;
namespace ConsoleApp1 
{
    class Program {       
        static void Main(string[] args)
        {
            char sr;
            string str;
            int i, freq = 0, flag = 0;
            Console.WriteLine("Enter Any String || Sentence || Word...");
            str = Console.ReadLine();

            Console.WriteLine("Enter Any Searching Character :");
            sr = char.Parse(Console.ReadLine());

            for (i=0;i<str.Length;i++)
            {
                if(str[i] == sr)
                {
                    flag = 1;
                    Console.WriteLine("At Position " + i);
                    freq++;
                }
            }
            if (flag == 1)
                Console.WriteLine("Character " + sr + " Occured " + freq + " Times ");
            else
                Console.WriteLine("Character Not Found ");
        }       
    }
}

Happy Coding…Thanks.

Post Author: adama