更改比較器實現自定義字串排序
輸入一個只包含大小寫字母的字串 按AaBbCc...的順序輸出
import java.util.Comparator;
//重寫比較器
public class C implements Comparator<Character>{
@Override
public int compare(Character c1, Character c2) {
Character cl1=Character.toLowerCase(c1);
Character cl2=Character.toLowerCase(c2); //轉換成小寫字母
if(cl1==cl2)
return c1.compareTo(c2);//相等再按原字母比較
else
return cl1.compareTo(cl2);
}
}
import java.util.Arrays;
import java.util.Scanner;
//測試
public class TestC {
public static void main(String[] args) {
String s=new Scanner(System.in).next();
Character [] a=new Character [s.length()];
for (int i = 0; i < a.length; i++) {
a[i]=s.charAt(i);
}
Arrays.sort(a, new C());
s="";
for (Character string : a) {
s=s+string;
}
System.out.println(s);
}
}