ASP.NET Hosting

Character Occurrence in a String in C#

In this article, I will discuss how to count the number of occurrences of a character in a string in C# in different ways. This detailed article will cover the following topics,

  1. Introduction
  2. Different ways to count character occurrence in a string in C#
  3. Conclusion

Character Occurrence in a String in C#’ is one of the most frequently asked questions in interviews. This tutorial will show you different ways to count the number of occurrences of a character in a string in C#.

Different ways to count character occurrence in a string in C#

Method. Using Loop to count character occurrence in a String in C#

In the following program, we take a string from the user, remove spaces from it, and then use a for loop to count the occurrence of each character in the string. Let’s see.

internal class UsingLoop
{
    static void Main(string[] args)
    {
        Console.Write("Enter the String: ");
        string str = Console.ReadLine();

        str = str.Replace(" ", string.Empty);   //Remove the empty spaces from the message

        while (str.Length > 0)
        {
            int count = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (str[0] == str[i])
                {
                    count++;
                }
            }
            Console.WriteLine($"Character '{str[0]}' appears {count} time(s) ");
            str = str.Replace(str[0].ToString(), string.Empty);
        }
        Console.ReadLine();
    }
}

Output

Method 2. Using a Dictionary to count the number of characters of a string in C#

In the following program, we take a string from the user, and then use a Dictionary to count the occurrence of each character in the string. Let’s see.

internal class UsingDictionary
{
    static void Main(string[] args)
    {
        Console.Write("Enter the string: ");
        string message = Console.ReadLine();

        message = message.ToLower();    // Optional: Convert the string to lowercase to ignore case sensitivity

        Dictionary<char, int> dict = new Dictionary<char, int>();

        foreach (char ch in message.Replace(" ", string.Empty))
        {
            if (dict.ContainsKey(ch))
            {
                dict[ch] = dict[ch] + 1;
            }
            else
            {
                dict.Add(ch, 1);
            }
        }
        foreach (var item in dict)
        {
            Console.WriteLine($"Character '{item.Key}' appears {item.Value} time(s)");
        }
        Console.ReadLine();
    }
}

Output

Method 3. Using Linq Group By to count the number of characters of a string in C#

In the following program, we take a string from the user, and then use the LINQ Group By method to count the occurrence of each character in the string. Let’s see.

internal class UsingLinqGroupBy
{
    static void Main(string[] args)
    {
        Console.Write("Enter the string: ");
        string str = Console.ReadLine();

        str = str.ToLower();    // Optional: Convert the string to lowercase to ignore case sensitivity

        Dictionary<char, int> dict = str.Replace(" ", string.Empty)
                                     .GroupBy(ch => ch)
                                     .ToDictionary(gb => gb.Key, gb => gb.Count());

        foreach (var item in dict.Keys)
        {
            Console.WriteLine($"Character '{item}' appears {dict[item]} time(s)");
        }
        Console.ReadLine();
    }
}

Output

Conclusion
In this article, we have discussed different ways to count the character occurrence of a string in C# with examples. I hope you enjoyed this blog. Follow C# Corner to learn more new and amazing things about C#.

Thanks for reading.

ASP.NET Core 8.0.8 Hosting Recommendation

HostForLIFE.eu
HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.