Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now

Character Occurrence in a String in C#

 

Character Occurrence in a String in C#

In this article, we will see the number of the character occurrence in a string.

private static void CharactersOccurrence()

{

  Console.Write("Enter the string : ");

    string inputString = Console.ReadLine();

  inputString = inputString.Replace(" ", string.Empty);



  while (inputString.Length > 0) {

    Console.Write(inputString[0] + " : ");

        int count = 0;

    for (int j = 0; j < inputString.Length; j++)

    {

      if (inputString[0] == inputString[j]) {

        count++;

      }

    }

    Console.WriteLine(count);

    inputString = inputString.Replace(inputString[0].ToString(), string.Empty);

  }

}

output




Using LINQ Group By method to count character occurrences in C#:

private static void CharactersOccurrence()

{

  Console.Write("Enter the string : ");

            string inputString = Console.ReadLine();

  Dictionary < char, int > dict = inputString.Replace(" ", string.Empty)

    .GroupBy(c => c)

    .ToDictionary(gr => gr.Key, gr => gr.Count());

  foreach(var item in dict.Keys)

  {

    Console.WriteLine(item + " : " + dict[item]);

  }



}


Output



Another way



static void Main()
    {
        string input = "hello world";
        Dictionary<char, int> charOccurrences = GetCharacterOccurrences(input);

        Console.WriteLine("Character Occurrences:");
        foreach (var kvp in charOccurrences)
        {
            Console.WriteLine($"'{kvp.Key}': {kvp.Value}");
        }
    }

    static Dictionary<char, int> GetCharacterOccurrences(string str)
    {
        Dictionary<char, int> charOccurrences = new Dictionary<char, int>();

        foreach (char c in str)
        {
            if (charOccurrences.ContainsKey(c))
            {
                charOccurrences[c]++;
            }
            else
            {
                charOccurrences[c] = 1;
            }
        }

        return charOccurrences;
    }



Share this

Related Posts

Previous
Next Post »

Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now