0
0
CsharpHow-ToBeginner · 3 min read

Count Occurrences of Character in String in C# - Simple Guide

In C#, you can count occurrences of a character in a string using string.Count(c => c == 'x') with LINQ. This counts how many times the character 'x' appears in the string.
📐

Syntax

Use the Count method from LINQ with a condition to count characters in a string.

  • stringVariable.Count(c => c == 'character'): Counts how many times 'character' appears.
csharp
int count = myString.Count(c => c == 'a');
💻

Example

This example shows how to count the number of times the letter 'e' appears in a sentence.

csharp
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string sentence = "Here is an example sentence.";
        int count = sentence.Count(c => c == 'e');
        Console.WriteLine($"The character 'e' appears {count} times.");
    }
}
Output
The character 'e' appears 6 times.
⚠️

Common Pitfalls

One common mistake is trying to use string.Length or string.IndexOf to count characters, which won't give the total count. Also, remember that character comparison is case-sensitive by default.

To count characters ignoring case, convert the string and character to the same case first.

csharp
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string text = "Hello World!";
        // Wrong: This only finds first index, not count
        int wrongCount = text.IndexOf('l');

        // Right: Count occurrences case-sensitive
        int countSensitive = text.Count(c => c == 'l');

        // Right: Count occurrences ignoring case
        int countIgnoreCase = text.ToLower().Count(c => c == 'l');

        Console.WriteLine($"Wrong count (IndexOf): {wrongCount}");
        Console.WriteLine($"Count case-sensitive: {countSensitive}");
        Console.WriteLine($"Count ignoring case: {countIgnoreCase}");
    }
}
Output
Wrong count (IndexOf): 2 Count case-sensitive: 3 Count ignoring case: 3
📊

Quick Reference

Remember these tips when counting characters in C# strings:

  • Use Count from System.Linq for easy counting.
  • Character comparison is case-sensitive by default.
  • Convert strings to lower or upper case to count ignoring case.
  • IndexOf finds position, not count.

Key Takeaways

Use LINQ's Count method with a condition to count character occurrences in a string.
Character comparison is case-sensitive unless you convert the string and character to the same case.
Avoid using IndexOf or Length to count characters as they do not provide total counts.
Include System.Linq namespace to use the Count method on strings.