Suppose user input a string and returns the character that occurs the most frequently in it.
Example - Aptara ---Here ans is a 3 times
1212332133733-- Here ans is 3
Suppose user input a string and returns the character that occurs the most frequently in it.
Example - Aptara ---Here ans is a 3 times
1212332133733-- Here ans is 3
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sachin SinghRank #66 · 26.2K reputationPosted Mar 1, 2023, 3:43 AM EST
The easiest would be
string str= "Aptara"; var maxCharWithCount= (from c in str group c by c into g select new { c = g.Key, count = g.Count(), }).OrderByDescending(c => c.count).first(); Console.WriteLine(maxCharWithCount.c + ": " + maxCharWithCount.count);Jignesh KumarRank #91 · 22.9K reputationPosted Mar 1, 2023, 3:17 AM EST
private static void GetMostFrequentCharacterFromString(string str) { Dictionary chars = new Dictionary(); foreach (char c in str.ToLower()) { if (chars.ContainsKey(c)) chars[c]++; else chars.Add(c, 1); } int max = chars.Values.Max(); var mostFoundCharacter = chars.Where(b => b.Value == max).Select(b => b.Key).First(); Console.WriteLine($"Most Count Found for {mostFoundCharacter} : {max}"); }Hi Rajeev,
Please try this code snippet,
Naimish MakwanaRank #324 · 7.7K reputationPosted Mar 1, 2023, 3:48 AM EST
Hello Rajeev,
Try below
string input = "Aptara "; char mostFrequent = input .GroupBy(c => c) .OrderByDescending(g => g.Count()) .First() .Key; Console.WriteLine("The most frequently occurring character is: " + mostFrequent);Thanks
Sardar Mudassar Ali KhanRank #18 · 48.8K reputationPosted Mar 1, 2023, 7:26 AM EST
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms { public class MaxChar { public char GetMostFrequentChar(string input) { var charMap = input.Distinct().ToDictionary(c => c, c => input.Count(s => s == c)); return charMap.OrderByDescending(kvp => kvp.Value).First().Key; } } }You can get help from the given below Code