Sort ignoring punctuation (Java)
Asked Answered
H

2

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.

Heaton answered 12/9, 2012 at 21:39 Comment(0)
S
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, ""));
};
Simone answered 12/9, 2012 at 21:43 Comment(2)
+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. CheersHeaton
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.Heaton
S
3

This should do it:

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

I don't think there is an easier way.

Shon answered 12/9, 2012 at 21:43 Comment(3)
This works if the only punctuation is the period. You can't use the String.replace method to replace multiple characters, but you can use String.replaceAllSimone
@JuanMendes Thanks, I am aware of that.Shon
The OP's example showed a period. But the question says punctuation.Simone

© 2022 - 2024 — McMap. All rights reserved.