【问题标题】:Sorting String List by rules [duplicate]按规则排序字符串列表[重复]
【发布时间】:2019-10-29 21:39:34
【问题描述】:

如何使用比较器或可比较基于 ACII 表对字符串列表进行升序或降序排序。

让我们假设一个字符串列表包含以数字 (1start) 或特殊字符 (@fill) 或小写 (kind) 或大写 (Link) 开头的单词

示例场景: 我想按以下特定顺序对列表进行排序:(排序为 asc 或 desc)

  • 以“小写”开头的单词应优先排序,
  • 以“特殊”字符开头的单词应排在第二位,
  • 以“数字”开头的单词应排在第三位,
  • 以“大写”开头的单词应排在第四位

【问题讨论】:

    标签: java string compare compareto lexicographic


    【解决方案1】:

    我会为这些“字符类”中的每一个创建一个枚举,并通过一些逻辑来确定每个字符属于哪个类:

    public enum CharacterClass {
        LOWERCASE, SPECIAL, NUMBER, UPPERCASE;
    
        public static CharacterClass getClass(char c) {
            if (Character.isLowerCase(c)) {
                return LOWERCASE;
            }
            if (Character.isUpperCase(c)) {
                return UPPERCASE;
            }
            if (Character.isDigit(c)) {
                return NUMBER;
            }
            return SPECIAL;
        }
    }
    

    在此基础上,我们现在可以创建一个比较器,它遍历两个字符串的字符并比较它们的类(然后是字符本身,如果它们具有相同的类):

    public class CharacterClassComparator implements Comparator<String> {
        @Override
        public int compare(String o1, String o2) {
            int l1 = o1.length();
            int l2 = o2.length();
            int length = Math.min(l1, l2);
    
            for (int i = 0; i < length; ++i) {
                char c1 = o1.charAt(i);
                char c2 = o2.charAt(i);
    
                // Compare the character classes
                int res = CharacterClass.getClass(c1).compareTo(CharacterClass.getClass(c2));
                if (res != 0) {
                    return res;
                }
    
                // If the clases are the same, compare the actual characters
                res = Character.compare(c1, c2);
                if (res != 0) {
                    return res;
                }
            }
    
            // All the characters up to the shared length are the same
            // Compare the lengths:
            return Integer.compare(l1, l2);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 2021-01-25
      • 2018-10-12
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 2014-06-19
      相关资源
      最近更新 更多