Find the most frequent character in a string with C# .NET
October 23, 2020 Leave a comment
Suppose you need a function that accepts a string and returns the character that occurs the most frequently in it. Examples:
Input | Result |
mamaaaa | a |
gaga | g |
agag | a |
12312312333456 | 3 |
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.:
Char | Count |
‘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"));
}
}
}