Count occurrences of a character
suggest changeBecause of the reasons explained in Remarks section you can’t simply do this (unless you want to count occurrences of a specific code-unit):
int count = text.Count(x => x == ch);
You need a more complex function:
public static int CountOccurrencesOf(this string text, string character) { return text.EnumerateCharacters() .Count(x => String.Equals(x, character, StringComparer.CurrentCulture)); }
Note that string comparison (in contrast to character comparison which is culture invariant) must always be performed according to rules to a specific culture.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents