您可以创建自己的Comparator
类/对象并将其传递给Arrays.sort()
. 不幸的是,您还需要将元素转换为Character
.
但是,也许最通用的方法是将每个字符视为 aString
并使用 a Collator
,如下例所示:
// Rules separated in 3 parts only for convenience
String rules1= "< A < B < C < D < E < F < G < H < I < J < K < L < M < N < O < P < Q < R < S < T < U < V < W < X < Y < Z" ;
String rules2= "< a < b < c < d < e < f < g < h < i < j < k < l < m < n < o < p < q < r < s < t < u < v < w < x < y < z" ;
String rules3= "< 0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9" ;
RuleBasedCollator collator= new RuleBasedCollator(rules1+rules2+rules3) ;
String input= "h498y948759hrh98A722hjDF94yugerTEr892ur48y" ;
// Bulk of the job done here
String[] arr= input.split("") ;
Arrays.sort(arr,1,arr.length,collator);
// Join back in a single string for presentation
StringBuilder sb= new StringBuilder() ;
for(String e: arr )
sb.append( e );
System.out.println(sb);
输出是
ADEFTeghhhhjrrrruuyyy222444457788888999999
仅将排序规则更改为
String rules1= "< 0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9" ;
String rules2= "< A,a < B,b < C,c < D,d < E,e < F,f < G,g < H,h < I,i < J,j < K,k < L,l < M,m < N,n < O,o < P,p < Q,q < R,r < S,s < T,t < U,u < V,v < W,w < X,x < Y,y < Z,z" ;
RuleBasedCollator collator= new RuleBasedCollator(rules1+rules2) ;
输出是
222444457788888999999ADEeFghhhhjrrrrTuuyyy
s的主要优点Collator
是它们允许根据其内部规则对多字符字符串进行排序。事实上,这是他们的主要用例。
很强大吧?(是的,我是加拿大人,以防你没猜到:-))