w3resource

C# Sharp Exercises: Highest frequency character(s) in the words of a string

C# Sharp String: Exercise-66 with Solution

Write a C# Sharp program to calculate the highest frequency of the character(s) in the words of a given string.

Sample Data:
("aaaaaa") -> "a"
("Century of the said year") -> ""
("CPP Exercises”) -> "s, e, p"

Sample Solution:

C# Sharp Code:

using System;
using System.Linq;
namespace exercises
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "aaaaaa";
            Console.WriteLine("Original strings: " + text);
            Console.WriteLine("Highest Frequency Character(s) in the said String: " + test(text));
            text = "Century of the said year";
            Console.WriteLine("\nOriginal strings: " + text);
            Console.WriteLine("Highest Frequency Character(s) in the said String: " + test(text));
            text = "CPP Exercises";
            Console.WriteLine("\nOriginal strings: " + text);
            Console.WriteLine("Highest Frequency Character(s) in the said String: " + test(text));            
        }

        public static string test(string text)
        {
            var groups = text.Reverse().GroupBy(ch => ch).OrderByDescending(
            el => el.Count());
            int max_occurs = groups.First().Count();
            if (max_occurs == 1) return "All unique characters";
            return string.Join(", ", groups.TakeWhile(
                  el => el.Count() == max_occurs).Select(el => el.Key));
        }
    }
}

Sample Output:

Original strings: aaaaaa
Highest Frequency Character(s) in the said String: a

Original strings: Century of the said year
Highest Frequency Character(s) in the said String:  

Original strings: CPP Exercises
Highest Frequency Character(s) in the said String: s, e, P

Flowchart :

Flowchart: C# Sharp Exercises - Highest frequency character(s) in the words of a string.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous C# Sharp Exercise: Find the century from a given year.
Next C# Sharp Exercise: Convert ASCII text to hexadecimal value as a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter