如何排序字母数字字符串 [英] How to sort Alphanumeric String
本文介绍了如何排序字母数字字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在排序包含整数的字符串时遇到问题。如果我使用下面的代码,我会得到如下排序:
1some,2some,20some,21some,3some,some
I have a problem with sorting strings which include integers. If I use the below code I get sorting like: 1some, 2some, 20some, 21some, 3some, some
但是我希望它排序如下:
1some,2some,3some,20some,21some,some
However I want it sorted like: 1some, 2some, 3some, 20some, 21some, some
我该怎么做?
谢谢!
Collections.sort(selectedNodes,
new Comparator<DefaultMutableTreeNode>() {
@Override
public int compare(DefaultMutableTreeNode o1,
DefaultMutableTreeNode o2) {
return o1.getUserObject().toString()
.compareTo(o2.getUserObject().toString());
}
});
推荐答案
这是一个关于如何做的自包含示例这个(没有特别优化):
Here is a self-contained example on how to do this (not particularly optimized):
final Pattern p = Pattern.compile("^\\d+");
String[] examples = {
"1some", "2some", "20some", "21some", "3some", "some", "1abc", "abc"
};
Comparator<String> c = new Comparator<String>() {
@Override
public int compare(String object1, String object2) {
Matcher m = p.matcher(object1);
Integer number1 = null;
if (!m.find()) {
return object1.compareTo(object2);
}
else {
Integer number2 = null;
number1 = Integer.parseInt(m.group());
m = p.matcher(object2);
if (!m.find()) {
return object1.compareTo(object2);
}
else {
number2 = Integer.parseInt(m.group());
int comparison = number1.compareTo(number2);
if (comparison != 0) {
return comparison;
}
else {
return object1.compareTo(object2);
}
}
}
}
};
List<String> examplesList = new ArrayList<String>(Arrays.asList(examples));
Collections.sort(examplesList, c);
System.out.println(examplesList);
输出
[1abc, 1some, 2some, 3some, 20some, 21some, abc, some]
解释
- 该示例使用常量
模式
推断一个数字是否在String
的起始位置。 - 如果第一个不存在
String
,它将其与第二个进行比较。 - 如果确实存在于第一个中,它会检查第二个。
- 如果第二个不存在,则按原样比较两个
String
,再次 - 如果在两者中,它比较
Integer
而不是整个String
s,因此导致数字比较而不是词典编纂 - 如果数字比较相同,则返回整个
String
s的字典比较(谢谢 MihaiC 发现这一个)
- The example uses a constant
Pattern
to infer whether a number is in theString
's starting position. - If not present in the first
String
, it compares it as is to the second. - If present indeed in the first, it checks the second.
- If not present in the second, it compares the two
String
s as is, again - If present in both, it compares the
Integer
s instead of the wholeString
s, hence resulting in a numerical comparison rather than a lexicographical one - If the number compare identical, it goes back to lexicographic comparison of the whole
String
s (thanks MihaiC for spotting this one)
这篇关于如何排序字母数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文