【问题标题】:Custom sort of the string ABCCAB to order BBAACC自定义排序字符串 ABCAB 以订购 BBAACC
【发布时间】:2018-01-10 12:14:51
【问题描述】:

如何尽可能简单地按自定义字母顺序对字符串进行排序?

示例:将字符串“ABCCAB”排序为“BBAACC”

【问题讨论】:

  • 你的意思是AABBCC
  • 你希望用什么逻辑来实现这个魔法?
  • 没有。那就是问题所在。排序必须是自定义的,而不是按字母顺序。
  • 如果是自定义排序,请举例说明将“ABCCAB”翻译成“BBAACC”的规则。
  • 制作您自己的排序比较器并使用它 - 有很多示例

标签: c#


【解决方案1】:

我已经整理了一个非常简单且不可靠的比较器演示。

正如@BugFinder 评论的那样,有数百个例子可以说明如何做到这一点。

我的示例只是为了让您开始自己的研究。

class Program
{
    public class MyComparer : IComparer<char>
    {
        private readonly Dictionary<char, int> _sortOrder;

        public MyComparer()
        {
            // This is just an example of simple logic based on your question.
            // The idea is you encapsulate the data your compare routine needs inside a custom comparer type
            // In this simple example I have created a lookup based on the final order of the characters in your question
            _sortOrder = new Dictionary<char, int> { { 'B', 0 }, { 'A', 1 }, { 'C', 2 } };
        }

        public int Compare(char x, char y)
        {
            // Again, this is just an example of how your main compare routine might work
            // The key is that the sort logic goes inside this method
            var precedenceLeft = _sortOrder[x];  // My example is seriously brittle.  This will crash for any characters that are not 'A', 'B' or 'C'
            var precedenceRight = _sortOrder[y];

            return precedenceLeft.CompareTo(precedenceRight);
        }
    }

    static void Main(string[] args)
    {
        // This code can be improved in numerous ways; this is just a simple example
        var chars = "ABCCAB".ToCharArray().ToList();

        chars.Sort(new MyComparer());  // You then give your customer comparer to the usual sort method

        var result = new string(chars.ToArray());

        Console.WriteLine(result);

        Console.ReadLine();
    }
}

This question here 提出了一个类似于我的解决方案。

或者,您可以采用为this question 建议的方法。

关键是,在本网站和整个互联网上,有数百种方法可以做到这一点。

【讨论】:

  • 就是这样!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-04
  • 1970-01-01
  • 2021-08-26
  • 2020-05-29
  • 2015-09-22
  • 1970-01-01
相关资源
最近更新 更多