[英]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.