从一种语言到另一种语言,对带有数字的字符串进行排序的方式不同。例如,在英语中,数字按升序排列在字母之前。但是,在德语中,数字是在字母之后升序排序的。
我尝试使用Collator
对字符串进行排序,如下所示:
private Collator collator = Collator.getInstance(Locale.GERMANY);
collator.compare(str1, str2)
但上面的比较没有考虑字母后面的数字规则。
有人知道为什么Java不考虑这个规则(字母后面的数字)吗?我现在使用RuleBasedCollator
,如下所示:
private final String sortOrder = "< 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 < 0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9";
private Collator collator = new RuleBasedCollator(sortOrder);
发布于 2012-11-23 22:55:30
您可以检查/调试源代码,以了解为什么没有任何变化:
Collator.getInstance(Locale.GERMANY);
调用以下块代码:
public static synchronized
Collator getInstance(Locale desiredLocale)
{
// Snipping some code here
String colString = "";
try {
ResourceBundle resource = LocaleData.getCollationData(desiredLocale);
colString = resource.getString("Rule");
} catch (MissingResourceException e) {
// Use default values
}
try
{
result = new RuleBasedCollator( CollationRules.DEFAULTRULES +
colString,
CANONICAL_DECOMPOSITION );
}
// Snipping some more code here
在这里,您可以看到特定的规则(colString
,在您的例子中无论如何都是空的)放在默认值(CollationRules.DEFAULTRULES
)之后。
正如您已经发现的,缺省值将数字放在最前面:
// NUMERICS
+ "<0<1<2<3<4<5<6<7<8<9"
+ "<\u00bc<\u00bd<\u00be" // 1/4,1/2,3/4 fractions
// NON-IGNORABLES
+ "<a,A"
+ "<b,B"
+ "<c,C"
+ "<d,D"
https://stackoverflow.com/questions/12778841
复制相似问题