tags:

views:

319

answers:

6

how can I calculate the number of repetition of character in string in c# ? example I have sasysays number of repetition of character 's' is 4

+2  A: 
for(int i=0; i < str.Length; i++) { 
    if(str[i] == myChar) {
        charCount++;
    }
}
glowcoder
+12  A: 

Here is a version using LINQ (written using extension methods):

int s = str.Where(c => c == 's').Count();

This uses the fact that string is IEnumerable<char>, so we can filter all characters that are equal to the one you're looking for and then count the number of selected elements. In fact, you can write just this (because the Count method allows you to specify a predicate that should hold for all counted elements):

int s = str.Count(c => c == 's');
Tomas Petricek
I tried in vs2008 and string does not seem to be IEnumerable.Can you verify.string.ToCharArray() is IEnumerable
josephj1989
@josephj1989, check again... http://msdn.microsoft.com/en-us/library/system.string.aspx
Thomas Levesque
In order for Intellisense to provide you with the LINQ extension methods, you might have to cast the string to `IEnumerable<char>`.
Phong
+2  A: 
s.Where(c => c == 's').Count()

given s is a string and you are looking for 's'

Keith Nicholas
+1  A: 
        string s = "sasysays ";
        List<char> list = s.ToList<char>();
        numberOfChar = list.Count<char>(c => c=='s');
Maurizio Reginelli
+4  A: 

Another option is:

int numberOfS = str.Count('s'.Equals);

This is a little backwards - 's' is a char, and every char has an Equals method, which can be used as the argument for Count.
Of course, this is less flexible than c => c == 's' - you cannot trivially change it to a complex condition.

Kobi
+1, pretty clever...
Thomas Levesque
Definitely clever, although certainly less intuitive than writing out `c => c == 's'` (I'd say that code is more likely to cause pause).
Phong
+2  A: 

A more general solution, to count number of occurrences of all characters :

var charFrequencies = new Dictionary<char, int>();
foreach(char c in s)
{
    int n;
    charFrequencies.TryGetValue(c, out n);
    n++;
    charFrequencies[c] = n;
}

Console.WriteLine("There are {0} instances of 's' in the string", charFrequencies['s']);
Thomas Levesque
Nice one, it is very possible more than one letter is needed, and calculating it once is a good idea. You can also write `s.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count());`, to achieve the same dictionary. I'm probably using too much LINQ `:P`
Kobi