例:将一组单词按照字典序输出
Five of the notes have two two two alternate equals sign Thus there are are are
String str = "Five of the notes have two two two alternate equals sign Thus there are are are";
//去除空格,保存为字符串数组类型
String[] arr = str.split("\\s+");
//重写Comparator接口的compare方法,默认为从小到大
Arrays.sort(arr, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
char[] arr1 = o1.toCharArray();
char[] arr2 = o2.toCharArray();
//较短字符串 比较 较长字符串前min位
int min = arr1.length < arr2.length?arr1.length:arr2.length;
//依次比较ASCII码大小
for (int i = 0; i < min; i++) {
//o1大于o2 则返回1
if(arr1[i]>arr2[i]) return 1;
else if(arr1[i]<arr2[i]) return -1;
}
//如果前min位都相同,则较长的>较短
if(arr1.length > arr2.length) return 1;
else if(arr1.length<arr2.length) return -1;
else return 0;
// compareTo(String anotherString)
// 按字典顺序比较两个字符串。
}
});
for (String string : arr) {
System.out.print(string+" ");
}
如过多次用可实现Comparator,重写compare
class SortByStr implements Comparator<String>{
@Override
public int compare(String o1, String o2) {
...
}
}
//使用
Arrays.sort(arr, new SortByStr());