In C#, What Is The Approach For Counting The Occurrences Of A Character Within A String?

There are several ways to count occurrences of a specific character within a string in C#. Here are a few examples:

  1. Using a loop:
string myString = "Hello World";
char myChar = 'o';

int count = 0;
foreach (char c in myString)
{
    if (c == myChar)
    {
        count++;
    }
}

Console.WriteLine("Occurrences of '{0}' in the string: {1}", myChar, count);
  1. Using LINQ:
string myString = "Hello World";
char myChar = 'o';

int count = myString.Count(c => c == myChar);

Console.WriteLine("Occurrences of '{0}' in the string: {1}", myChar, count);
  1. Using regular expressions:
string myString = "Hello World";
char myChar = 'o';

int count = Regex.Matches(myString, Regex.Escape(myChar.ToString())).Count;

Console.WriteLine("Occurrences of '{0}' in the string: {1}", myChar, count);

All three approaches will provide the same result, which is the count of occurrences of the specified character within the string.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!