Home > OS >  How can I sort numbers from largest to smallest in this code block?
How can I sort numbers from largest to smallest in this code block?

Time:04-21

In the printout, numbers will be listed from largest to smallest and the letters will be written next to them.

        Console.Write("Enter Sentence : ");
        String sentence = Console.ReadLine();
        Console.WriteLine("-----------------------------");
        sentence = sentence.ToLower();
        String characters = "0123456789abcdefghijklmnopqrstuvwxyz.?,;";
        int[] count = new int[characters.Length];
        for (int i = 0; i < sentence.Length; i  )
        {
            int index = characters.IndexOf(sentence[i]);
            if (index < 0)
                continue;
            else
            {
                count[index]  ;
            }
        }
        for (int i = 0; i < count.Length; i  )
        {
            if (count[i] < 1)
                continue;
            else
            {
                Console.WriteLine(" "   characters[i]   " = "   count[i]);
            }
            Console.WriteLine("-----------------------------");
        }
        Console.ReadKey();

CodePudding user response:

I would use a Dictionary<char, int> to count the occurence of each char in that sentence. That's the most efficient way. Then you can use a simple one-liner LINQ to order it by count:

sentence = sentence.ToLower();
var charCounter = new Dictionary<char, int>(sentence.Length);
foreach(char c in sentence)
{
    charCounter.TryGetValue(c, out int count);
    charCounter[c] =   count;
}

foreach(var kv in charCounter.OrderByDescending(kv => kv.Value))
{
    Console.WriteLine($"{kv.Key} = {kv.Value}");
}
  •  Tags:  
  • c#
  • Related