Showing posts with label find most repeated character in given string. Show all posts
Showing posts with label find most repeated character in given string. Show all posts

Wednesday, March 11, 2020

How to find most repeated character in given string using c#

The below code to  find most repeated character in given string in c#.


using System;

namespace MostRepeatedCharacter
{
    class Program
    {
        static Char GetMostRepeatedChar(string str)
        {
             // declare integer Array to count number of most repeated characters. 
            int[] count = new int[256];
            int Max = 0;
            Char result = Char.MinValue;

         // Traversing each character from left to right.
            foreach (Char c in str)
            {
               // To check if empty space and collecting repeated characters here.
                if (c !=' ' && ++count[c] > Max)
                {
                    Max = count[c];

                    result = c;
                }
            }
            return result;
        }
        static void Main(string[] args)
        {
            
            string str = "SWISS";
            Console.WriteLine("Most repeated character '{0}'", GetMostRepeatedChar(str));
            Console.ReadLine();
        }
    }
}


Out put : Most repeated character: S.