Program to find how many times a character repeated in a given string using C#

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 2290
Suppose we have a string and we need to figure out how many characters have been repeated.The below code will help to do so

using System;
using System.Linq;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string lstWords = "hello this is dotnet funda";
(from character in lstWords.ToCharArray().Where(x => !Char.IsWhiteSpace(x))
group character by character into g
select new
{
Characters = g.Key,
RepeatedCharacters = (g.Count() - 1) == 0
? String.Concat("Character ", g.Key, " has never repeated")
: String.Concat("Character ", g.Key, " repeated ", g.Count(), " times")
}).ToList().ForEach(i => Console.WriteLine("{0} : {1}", i.Characters, i.RepeatedCharacters));
Console.ReadKey(true);
}
}
}

Observe that we are removing the WhiteSpaces. Final output

h : Character h repeated 2 times
e : Character e repeated 2 times
l : Character l repeated 2 times
o : Character o repeated 2 times
t : Character t repeated 3 times
i : Character i repeated 2 times
s : Character s repeated 2 times
d : Character d repeated 2 times
n : Character n repeated 2 times
f : Character f has never repeated
u : Character u has never repeated
a : Character a has never repeated

Hope this will be helpful.

Comments or Responses

Login to post response