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
Take a string str. Take n as integer, ch as character and length of str as integer. Function occurrences_char(string str, int length, int n, char ch) takes str, ch, n and length of str and returns the count of ch in first n characters in repeated string str. Take the initial count as 0.
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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With