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
for(int i=0; i < str.Length; i++) {
if(str[i] == myChar) {
charCount++;
}
}
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');
s.Where(c => c == 's').Count()
given s is a string and you are looking for 's'
string s = "sasysays ";
List<char> list = s.ToList<char>();
numberOfChar = list.Count<char>(c => c=='s');
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.
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']);