繁体   English   中英

如何在此代码块中从大到小对数字进行排序?

[英]How can I sort numbers from largest to smallest in this code block?

在打印输出中,数字将从大到小列出,字母将写在它们旁边。

        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();

我会使用Dictionary<char, int>来计算该句子中每个字符的出现次数。 这是最有效的方法。 然后你可以使用一个简单的单行 LINQ 按计数排序:

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}");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM