结合字母顺序和自然顺序(又名用户理智排序) [英] Combine alphabetical and natural order (aka. User sane sorting)

查看:97
本文介绍了结合字母顺序和自然顺序(又名用户理智排序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这很容易找到预制的,但似乎我在网上找到的任何解决方案都只能解决部分问题.

I thought this would be easy to find premade, but it seems any solution I can find on the web solves only part of the problem.

我想对用户提供的文件名(文件大多以人和/或地址命名)的列表进行排序,有时以不同的语言(大多数为德语,用到处都混有一些法国和意大利文,很少有其他西方语言.

I want to sort a list of Filenames (and the files have mostly been named after persons and/or addresses) that have been given by users, sometimes in different languages (mostly german, with a bit of french and italian mixed in here and there, and rarely any other western language).

这个想法是按照(德语)用户通常认为理智的方式来排序此列表.这意味着该顺序应遵循 java.text.Collat​​or for Locale.GERMAN ,但同时期望对字符串中的数字进行例外处理,因此"10"在"2"之后.

The idea is to present this list ordered in a way that the (german) users generally deem sane. That means the order should follow the java.text.Collator for Locale.GERMAN, but at the same time the expectation is to make an exception for numbers in the string, so "10" comes after "2".

我发现代码可以在网络上进行自然排序,但是它依靠逐个字符进行比较(而Collat​​or不支持).我可以用子字符串破解某些东西,但是在比较器内部,这并不是我最聪明的主意,因为每个比较调用都可以创建多个子字符串.

I have found code to do the natural sorting on the web, but it relies on comparing character by character (and Collator doesn't support that). I could hack something with substring, but inside a comparator it doesn't deem me the brightest idea to create multiple substrings on each compare-call.

有什么想法如何有效地实现这一目标(在执行时间和实现时间内),或者更好地是经过测试且可以立即使用的实现?

Any ideas how to implement this efficiently (in both execution time and implementation time), or better yet a tested and ready-to-use implementation?

推荐答案

如果使用@millimoose(http://www.davekoelle.com/alphanum.html)建议的比较器,请对其进行修改以通过整理程序

If you use the Comparator suggested by @millimoose (http://www.davekoelle.com/alphanum.html) modify it to pass the Collator

public class AlphanumComparator implements Comparator
{
private Collator collator;
public AlphanumComparator(Collator collator) {
    this.collator = collator;
}
.....
    public int compare(Object o1, Object o2)
    {
......
result = thisChunk.compareTo(thatChunk); //should become
collator.compare(thisChuck, thatChuck);
....

此代码似乎有问题,例如"01"比"2"大.但这取决于您的喜好,如果这很重要,请修改它以在进行数字比较之前跳过前导零.

this code seems to have a problem, for example "01" is grater then "2". But this depends on you preference, if this is important modify it to skip the leading zeros before number compare.

这篇关于结合字母顺序和自然顺序(又名用户理智排序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆