How to find the number of occurences of a digit in a given number?


This article would provide you with a small LINQ code snippet to find out the number of occurence of a particular digit in the input without converting its datatype.

The following code snippet accepts a number and validates it. If the input is valid then it will give the number of occurrences of all the digits in the entered number with out parsing or converting it to other datatypes using LINQ.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.IO;

namespace MyLibrary
{
class OccurenceCount
{
static void Main(string[] args)
{
Console.WriteLine("Enter numbers: ");
List def = new List();//int list to hold input

//temp variables
int x;
char ch;

//Read input characters until carriage return
do
{
x = Console.Read();
ch = Convert.ToChar(x);
if (Char.IsWhiteSpace(ch))
{
break;
}

//check for invalid characters. use catch block to catch the exception
else if (!Char.IsNumber(ch))
{
throw new Exception("NO ALPHABETS OR SPECIAL CHARACTERS ARE ALLOWED");
}
else
{
def.Add(x - 48);
}
} while (true);

//linq to list
var results = from res in def
group res by res into tempo
select new { name = tempo.Key, count = tempo.Count() };

foreach (var r in results)
{
Console.WriteLine(r.name+" occurs {0} times: ",r.count);
}

Console.ReadLine();
Console.ReadLine();
}
}
}


The output would be like this:


Enter numbers:
23233452

2 occurs 3 times
3 occurs 3 times
4 occurs 1 times
5 occurs 1 times


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: