Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now

Get highest occurred character and minimum occurred character in a String using C#

 

Get highest occurred character and minimum occurred  character in a String

public static void GetHighestAndMinCharFromString()

        {

            String str = "grass is greener on the other sidee";

            int[] freq = new int[str.Length];

            char minChar = str[0], maxChar = str[0];

            int i, j, min, max;

 

            //Converts given string into character array 

            char[] string1 = str.ToCharArray();

 

            //Count each word in given string and store in array freq 

            for (i = 0; i < string1.Length; i++)

            {

                freq[i] = 1;

                for (j = i + 1; j < string1.Length; j++)

                {

                    if (string1[i] == string1[j] && string1[i] != ' ' && string1[i] != '0')

                    {

                        freq[i]++;

 

                        //Set string1[j] to 0 to avoid printing visited character 

                        string1[j] = '0';

                    }

                }

            }

 

            //Determine minimum and maximum occurring characters 

            min = max = freq[0];

            for (i = 0; i < freq.Length; i++)

            {

 

                //If min is greater than frequency of a character  

                //then, store frequency in min and corresponding character in minChar 

                if (min > freq[i] && freq[i] != '0')

                {

                    min = freq[i];

                    minChar = string1[i];

                }

                //If max is less than frequency of a character  

                //then, store frequency in max and corresponding character in maxChar 

                if (max < freq[i])

                {

                    max = freq[i];

                    maxChar = string1[i];

                }

            }

 

            Console.WriteLine("Minimum occurring character: " + minChar + " Count = " + min);

            Console.WriteLine("Maximum occurring character: " + maxChar + " Count = " + max);

            Console.ReadLine();

        }


Output



Share this

Related Posts

Previous
Next Post »

Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now