Count of number for individual char in string ???

Sabarimahesh
Posted by Sabarimahesh under C# category on | Points: 40 | Views : 1296
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
public static class Program
{

static void Main(string[] args)
{
string aa = "sabarimahesh";
char aaa = 'a';
Console.WriteLine(Individualchar(aa, aaa));
Console.ReadLine();
}

public static int Individualchar(string srtingsr, char Charfind)
{
int cnt = 0;
char[] ch = srtingsr.ToCharArray();
foreach (char c in ch)
{
if (c == Charfind)
{
cnt++;
}
}
return cnt;
}


}
}

Comments or Responses

Posted by: Niladri.Biswas on: 6/1/2012 Level:Platinum | Status: [Member] | Points: 10
Hi,
This can also be done using group by of linq

string input = "sabarimahesh";

char searchFor = 'm';

(from letter in input.ToCharArray()
group letter by letter into g
select new
{
Letters = g.Key

,
LetterCount = g.Count()
})
.Where(i => i.Letters == searchFor)
.ToList()
.ForEach(i => Console.WriteLine(i.LetterCount));


OR Lambda

input

.ToCharArray()
.GroupBy(i => i)
.Select(i => new { Letters = i.Key, LetterCount = i.Count() })
.Where(i => i.Letters == searchFor)
.ToList()
.ForEach(i => Console.WriteLine(i.LetterCount));

Login to post response