【问题标题】:Is it possible to change priority(weight) of certain symbols in sorting?是否可以在排序中更改某些符号的优先级(权重)?
【发布时间】:2019-04-08 14:01:05
【问题描述】:

我想为字符串值创建一个比较器,但根据https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html,下划线符号的值比任何数字都大。能不能改一下?

【问题讨论】:

  • 你说的是下划线任意数字。你在比较人物吗?你现在如何比较它们?
  • 现在我只使用 string.compareTo(string2)

标签: java string gwt compare comparator


【解决方案1】:

这可能有效:

private int compareStrings(String o1, String o2) {
    if(o1.matches("\\d+") && o2.equals("_")) {
        return 1;
    }
    if(o1.equals("_") && o2.matches("\\d+")) {
        return -1;
    }
    return o1.compareTo(o2);
}

然后像这样定义你的比较器:

Comparator<String> stringComparator2 = this::compareStrings;

编辑:

根据不适用于中间带有_的字符串,如何将_替换为ASCII表中之前的字符以进行比较(例如" "):

public static int compareStrings(String o1, String o2) {
    o1 = o1.replaceAll("_", " ");
    o2 = o2.replaceAll("_", " ");
    return o1.compareTo(o2);
}

【讨论】:

  • 在将字符串与中间的_ 进行比较时,您的解决方案将无法正常工作。
【解决方案2】:

简答

是的,是的。您需要一个自定义字符串比较器。

解决方案

假设您需要对字符串列表进行排序:

[a_123, ab123, a123, 123, _123]

如果您使用Collections.sort 对其进行排序,那么它将按以下顺序排序:

[123, _123, a123, a_123, ab123]

但您想覆盖_ 的“权重”。为此,您需要一个自定义字符串比较器。我们复制修改一下java.lang.String#compareTo

private int customStringComparator(String s1, String s2) {
    int len1 = s1.length();
    int len2 = s2.length();
    int lim = Math.min(len1, len2);
    char v1[] = s1.toCharArray();
    char v2[] = s2.toCharArray();

    int k = 0;
    while (k < lim) {
        char c1 = v1[k];
        char c2 = v2[k];
        // You can add your custom comparison here:
        if ('_' == c1 && Character.isDigit(c2)) {
            // We intentionally return inverted result
            return c2  - c1;
        }else if(c1 != c2) {
            return c1 - c2;
        }
        k++;
    }
    return len1 - len2;
}

现在我们可以将customStringComparator 传递给Collections.sort

Collections.sort(list, this::customStringComparator);

列表将按以下顺序排序:

[_123, 123, a_123, a123, ab123]

如您所见,现在_ 位于数字之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-22
    • 2021-03-28
    • 2021-07-02
    • 2020-03-16
    • 2014-08-05
    • 2017-01-09
    • 2021-03-06
    • 2021-06-16
    相关资源
    最近更新 更多