To get count of occurance of character in string using c#

Posted by Sangeetha Mani under C# on 10/26/2013 | Points: 10 | Views : 1057 | Status : [Member] | Replies : 2
Hi friends,

How to get count of occurrence of character in string using C#?

sangeetha.m


Responses

Posted by: Bandi on: 10/26/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
http://www.dotnetperls.com/string-occurrence




Simple aproach

string haystack ="/once/upon/a/time";
string needle ="/";
int needleCount =( haystack.Length- source.Replace(needle,"").Length)/ needle.Length


If you're using .NET 3.5 you can do this in a one-liner with LINQ:

int count = source.Count(f => f =='yourSearchChar');


If you don't want to use LINQ you can do it with:

int count = source.Split('yourSearchChar').Length-1;


Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Sangeetha Mani, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bandi on: 10/26/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
Refer
http://www.dotnetperls.com/string-occurrence
http://www.dotnetfunda.com/forums/show/16681/to-get-count-of-occurance-of-character-in-string-using-csharp

Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Sangeetha Mani, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response