Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate number of repetition of character in string in c#

Tags:

string

c#

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

like image 737
kartal Avatar asked May 24 '10 21:05

kartal


People also ask

How do I count the number of repeated characters in a string in C++?

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.


2 Answers

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');
like image 102
Tomas Petricek Avatar answered Oct 18 '22 06:10

Tomas Petricek


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.

like image 27
Kobi Avatar answered Oct 18 '22 05:10

Kobi