Find the most frequent character in a string with C# .NET

Suppose you need a function that accepts a string and returns the character that occurs the most frequently in it. Examples:


Note that we’ll treat numeric values as strings. Also, with multiple values having the same max we’ll return the first one.

We’ll build a character map out of the input string, just like the one we saw in this post. Here’s a reminder:

What is a character map? It is a map where the key is of type char and the value if of type integer. We collect the unique characters of a string and count how many times each character occurs in the string. E.g.:


We’ll reuse the same method as in the referenced post.

Then we sort the map by the values in descending order and return the key of the key-value pair on top:

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;

Here comes a short set of unit tests:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Algorithms;
using System;
using System.Collections.Generic;
using System.Text;

namespace Algorithms.Tests
    public class MaxCharTests
        public void GetMostFrequentCharTests()
            MaxChar mc = new MaxChar();
            Assert.AreEqual('a', mc.GetMostFrequentChar("mamaaaa"));
            Assert.AreEqual('g', mc.GetMostFrequentChar("gaga"));
            Assert.AreEqual('a', mc.GetMostFrequentChar("agag"));
            Assert.AreEqual('3', mc.GetMostFrequentChar("12312312333456"));


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: