问题描述:

Currently I have some code that takes filenames and sorts them in some different ways (locale-sensitive natural sort, case-insensitive ASCIIbetical sort, by modified date, etc.), for example, for locale-sensitive natural sort it uses this:

Collections.sort(files, new Comparator<File>() {

@Override

public int compare(File f1, File f2) {

return NaturalComparator.compareNatural(collator, f1.getName(), f2.getName());

}

});

I would like to know how to make it ignore the word "the" at the beginning of a filename, so the instead of ordering files like this:

Apple

Carrot

The Banana

It orders them like this:

Apple

The Banana

Carrot

网友答案:

You can replace the first occurrence of The before passing it to comparator, using String#replaceFirst(regex, replacement) or String.replaceAll(regex, replacement) methods, both of which take a regex as parameter to replace, and both can be used here: -

@Override
public int compare(File f1, File f2) {
    return NaturalComparator.compareNatural(collator, 
                                          f1.getName().replaceAll("^(?i)The ", ""), 
                                          f2.getName().replaceAll("^(?i)The ", ""));
}  

Added a (?i) flag before the regex pattern to do a case insensitive replace (Thanks to @Chris for pointing this).

Caret (^) is added before the pattern, so that it replaces only the The at the beginning of the string. So, The banana will be replaced with banana, but Banana, The will not be replaced with Banana,. It will remain the same.

网友答案:
Collections.sort(files, new Comparator<File>() {
    @Override
    public int compare(File f1, File f2) {
        return NaturalComparator.compareNatural(collator, f1.getName().startsWith("The  ")?f1.getName().substring(4) : f1.getName(), f2.getName().startsWith("The ")?f2.getName().substring(4):f2.getName();
    }
});
网友答案:
static String ignoreThe(String s) {
    if (s.length > 3) {
        if (s.substring(0, 4).toLowerCase().equal("the ")) {
            return s.substring(0, 4);
        }
    }
    return s;
}

Collections.sort(files, new Comparator<File>() {
    @Override
    public int compare(File f1, File f2) {
        String name1 = ignoreThe(f1.getName()); 
        String name1 = ignoreThe(f2.getName()); 
        return name1.compareTo(name2);
    }
});
网友答案:

try

...
return NaturalComparator.compareNatural(collator, f1.getName().replaceAll("^The ", ""), f2.getName().replaceAll("^The ", ""));
相关阅读:
Top