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:

InputResult
mamaaaaa
gagag
agaga
123123123334563

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.:

CharCount
‘f’2
‘g’1
‘i’2
‘d’1
‘o’1

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
{
    [TestClass()]
    public class MaxCharTests
    {
        [TestMethod()]
        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:

WordPress.com Logo

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

Google photo

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

Twitter picture

You are commenting using your Twitter 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

HarsH ReaLiTy

A Good Blog is Hard to Find

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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

%d bloggers like this: