3

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.

CaptainProg
  • 5,610
  • 23
  • 71
  • 116

2 Answers2

4

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, ""));
};
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • +1 for the remove string. For me, Baz's solution worked though since it doesn't use replaceAll. No idea why replaceAll doesn't work, but I like the idea of having the remove characters in a string. Cheers – CaptainProg Sep 12 '12 at 21:52
  • Okay, your solution now works better! It causes a bit of an increase in my load time, and in practise I'll be using Baz's method (for my specific application I'd choose only one character removal over the load time), but yours answers my question for multiple punctuation types. – CaptainProg Sep 12 '12 at 22:00
3

This should do it:

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

I don't think there is an easier way.

Baz
  • 36,440
  • 11
  • 68
  • 94