Sort ignoring punctuation (Java)

 ̄綄美尐妖づ 提交于 2019-12-13 14:45:40

问题


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.



来源:https://stackoverflow.com/questions/12396540/sort-ignoring-punctuation-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!