67,517
社区成员
发帖
与我相关
我的任务
分享
String[] array = new String[] {
"D1", "D11", "D12", "D13", "D2", "D3", "H", "F0", "h1", "h0", "f1",
"F2", "d9", "1"
};
// 假设所有情况都是字母在前,数字在后
Comparator<String> cmp = new Comparator<String>() {
public int compare(String str1, String str2) {
// 字母部分
String alphabet1 = str1.replaceAll("\\d+$", "");
String alphabet2 = str2.replaceAll("\\d+$", "");
// 如果不想区分大小写,否则compareTo
int cmpAlphabet = alphabet1.compareToIgnoreCase(alphabet2);
if (cmpAlphabet != 0) {
return cmpAlphabet;
}
// 数字部分
String numeric1 = str1.replaceAll("^[a-zA-Z]+", "");
String numeric2 = str2.replaceAll("^[a-zA-Z]+", "");
if ("".equals(numeric1)) {
// 即使numeric2也是空串也无所谓,当然,如果比较的不是String(或其他immutable对象)则另当别论
return -1;
}
if ("".equals(numeric2)) {
return 1;
}
int num1 = Integer.parseInt(numeric1);
int num2 = Integer.parseInt(numeric1);
return num1 - num2;
}
};
Arrays.sort(array, cmp);
System.out.println(Arrays.toString(array));
}
String ss[] = {"D12","D2","D03","B","D11","D8","D12","H","F0"};
Arrays.sort(ss);
for(String s : ss){
System.out.print(s+",");
}