Sort ignoring punctuation (Java)

2019-07-13 00:43发布

问题:

I am trying to sort an Android ListView object. I am currently using the following code:

  // Sort terms alphabetically, ignoring case
  adapter.sort(new Comparator<String>() {
        public int compare(String object1, String object2) {
            return object1.compareToIgnoreCase(object2);
        };

This sorts my list, whist ignoring case. However, it would be nice to ignore punctuation as well. For example:

c.a.t.
car
cat

should be sorted as follows:

car
c.a.t.
cat

(It doesn't actually matter which of the two cats (cat or c.a.t.) comes first, so long as they're sorted next to one another).

Is there a simple method to get around this? I presume the solution would involve extracting JUST the alphanumeric characters from the strings, then comparing those, then returning them back to their former states with the non-alphanumeric characters included again.

回答1:

When you compare, remove the characters you don't care about

public int compare(String str1, String str2) {
    String remove = "[\\.:',]"; // change this to all to characters to remoce
    return str1.replaceAll(remove, "").compareToIgnoreCase(object2.replaceAll(remove, ""));
};


回答2:

This should do it:

return object1.replace(".", "").compareToIgnoreCase(object2.replace(".", ""));

I don't think there is an easier way.