![](/img/trans.png)
[英]How to sort strings where a string contains alpha numeric characters like ROLL-10 > ROLL-2
[英]how to sort Aplha numeric strings?
我有一个字符串字符列表,它们是混合字符,也包括特殊字符。 我想知道如何对它们进行升序排序?
更新的示例aplha1.jpg aplha10.jpg 2.jpg 3.jpg 4.jpg aplha5.jpg
Tom Christiansen(@tchrist)暗示的是,为了比较文本,您通常应使用Collator java.text.Collator ,它应考虑真实的字母顺序(可能包括特定于语言环境的规则),而不仅仅是Unicode代码单位的字典顺序。
要进行排序,您可以将每个String
转换为CollationKey
,然后对CollationKey
。 这样做是为了提高效率,您也可以使用整理程序直接对字符串进行排序,但是这样做的效果会更差。
字符串实现Comparable。
将您的字符串放入ArrayList或数组中,然后分别在它们上调用Collections.sort()
或Arrays.sort()
。
仅在有特殊需要时,才需要使用Comparator
。 只是不要推出自己的“怪癖”。
希望这对您有用。
public class AlphanumericSorting implements Comparator<String> {
public int compare(String firstObjToCompare, String secondObjToCompare) {
String firstString = firstObjToCompare.toString();
String secondString = secondObjToCompare.toString();
if (secondString == null || firstString == null) {
return 0;
}
int lengthFirstStr = firstString.length();
int lengthSecondStr = secondString.length();
int index1 = 0;
int index2 = 0;
while (index1 < lengthFirstStr && index2 < lengthSecondStr) {
char ch1 = firstString.charAt(index1);
char ch2 = secondString.charAt(index2);
char[] space1 = new char[lengthFirstStr];
char[] space2 = new char[lengthSecondStr];
int loc1 = 0;
int loc2 = 0;
do {
space1[loc1++] = ch1;
index1++;
if (index1 < lengthFirstStr) {
ch1 = firstString.charAt(index1);
} else {
break;
}
} while (Character.isDigit(ch1) == Character.isDigit(space1[0]));
do {
space2[loc2++] = ch2;
index2++;
if (index2 < lengthSecondStr) {
ch2 = secondString.charAt(index2);
} else {
break;
}
} while (Character.isDigit(ch2) == Character.isDigit(space2[0]));
String str1 = new String(space1);
String str2 = new String(space2);
int result;
if (Character.isDigit(space1[0]) && Character.isDigit(space2[0])) {
Integer firstNumberToCompare = new Integer(Integer.parseInt(str1.trim()));
Integer secondNumberToCompare = new Integer(Integer.parseInt(str2.trim()));
result = firstNumberToCompare.compareTo(secondNumberToCompare);
} else {
result = str1.compareTo(str2);
}
if (result != 0) {
return result;
}
}
return lengthFirstStr - lengthSecondStr;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.