20 June 2011

Find the most occurrence of a character in string using C#

Hi All,
Got time after long time for posting something. :)

Recently I came across to a requirement in one of my project to find the specific
character occurrence from the given string.  There are various
methods to achieve this kind of functionality as individual can have their own logic.
I have tried to achieve this with LINQ and C#. Here I am sharing my efforts.

public void FindCharacterOccurrence(string input)
        {           
            if (!string.IsNullOrEmpty(input))
            {


                var outputMin = (from c in input
                                 where c != ' '
                                 group c by c into g
                                 select new
                                 {
                                     c = g.Key,
                                     count = g.Count(),
                                 }).OrderByDescending(c => c.count).Last();                
                


                var outputMax = (from c in input
                                 where c != ' '
                                 group c by c into g
                                 select new
                                 {
                                     c = g.Key,
                                     count = g.Count(),
                                 }).OrderByDescending(c => c.count).First();


                Response.Write(outputMax.count + ":" + outputMax.c);


                var outputAll = (from c in input
                              where c != ' '
                              group c by c into g
                              select new
                              {
                                  c = g.Key,
                                  count = g.Count(),
                              }).OrderByDescending(c => c.count);




                StringBuilder strOutput = new StringBuilder();
                strOutput.Append("
");
                strOutput.Append("
");
                foreach (var item in outputAll)
                {
                    strOutput.Append("
");
                }
                strOutput.Append("
Character
Count
" + item.c + "
" + item.count + "
");


                ltrOutput.Text = strOutput.ToString();//output to Literal control
            }
        }
Features:
  1. It will not count space.
    If you want to count space then please remove WHERE condition from the query.
  2. You can get minimum
    and maximum character count
    also.
Hope you will find it helpful.

Please feel free to provide your comments/suggestions.