排序忽略标点(Java) [英] Sort ignoring punctuation (Java)

查看:108
本文介绍了排序忽略标点(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对Android ListView对象进行排序.我目前正在使用以下代码:

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

应按以下顺序排序:

car
c.a.t.
cat

(两只猫(哪只猫是猫还是c.a.t.)先出现,实际上并不重要,只要它们紧挨着排序即可.)

(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.

推荐答案

比较时,删除不需要的字符

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, ""));
};

这篇关于排序忽略标点(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆