Count occurrences of a character

suggest change

For the reasons explained in the Remarks section of Strings, 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));
}

String comparison, unlike char comparison, is not culture-invariant. Compare text elements with the rules of a specific culture.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents