是否可以在排序中更改某些符号的优先级(权重)?

我想为字符串值创建一个比较器,但根据https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html下划线符号比任何数字都具有更大的价值。有可能以某种方式改变它吗?


www说
浏览 195回答 2
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) {&nbsp; &nbsp; int len1 = s1.length();&nbsp; &nbsp; int len2 = s2.length();&nbsp; &nbsp; int lim = Math.min(len1, len2);&nbsp; &nbsp; char v1[] = s1.toCharArray();&nbsp; &nbsp; char v2[] = s2.toCharArray();&nbsp; &nbsp; int k = 0;&nbsp; &nbsp; while (k < lim) {&nbsp; &nbsp; &nbsp; &nbsp; char c1 = v1[k];&nbsp; &nbsp; &nbsp; &nbsp; char c2 = v2[k];&nbsp; &nbsp; &nbsp; &nbsp; // You can add your custom comparison here:&nbsp; &nbsp; &nbsp; &nbsp; if ('_' == c1 && Character.isDigit(c2)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // We intentionally return inverted result&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return c2&nbsp; - c1;&nbsp; &nbsp; &nbsp; &nbsp; }else if(c1 != c2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return c1 - c2;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; k++;&nbsp; &nbsp; }&nbsp; &nbsp; return len1 - len2;}现在我们可以将我们的传递customStringComparator给Collections.sort:Collections.sort(list, this::customStringComparator);该列表将按以下顺序排序:[_123, 123, a_123, a123, ab123]如您所见,现在_前面的数字。

慕哥6287543

这可能有效:private int compareStrings(String o1, String o2) {&nbsp; &nbsp; if(o1.matches("\\d+") && o2.equals("_")) {&nbsp; &nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; }&nbsp; &nbsp; if(o1.equals("_") && o2.matches("\\d+")) {&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; }&nbsp; &nbsp; return o1.compareTo(o2);}然后像这样定义你的比较器:Comparator<String> stringComparator2 = this::compareStrings;编辑:根据不为_中间的字符串工作,如何仅替换_为 ASCII 表中之前的字符以进行比较(" "例如):public static int compareStrings(String o1, String o2) {&nbsp; &nbsp; o1 = o1.replaceAll("_", " ");&nbsp; &nbsp; o2 = o2.replaceAll("_", " ");&nbsp; &nbsp; return o1.compareTo(o2);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java