对可能包含数字的字符串进行排序 [英] Sort on a string that may contain a number

查看:34
本文介绍了对可能包含数字的字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个比较字符串的 Java Comparator 类,但是有一个转折.如果它比较的两个字符串相同,首尾相同,中间不同的部分是一个整数,则根据这些整数的数值进行比较.例如,我希望以下字符串以显示顺序结束:

  • aaa
  • bbb 3 ccc
  • bbb 12 ccc
  • ccc 11
  • dd
  • eee 3 ddd jpeg2000 eee
  • eee 12 ddd jpeg2000 eee

如您所见,字符串中可能还有其他整数,因此我不能仅使用正则表达式来拆分任何整数.我正在考虑从一开始就遍历字符串,直到找到不匹配的位,然后从最后进入,直到找到不匹配的位,然后将中间的位与正则表达式[0-9]+",如果比较就做数值比较,否则做词法比较.

有更好的方法吗?

更新 我不认为我可以保证字符串中的其他数字,可能匹配的数字,周围没有空格,或者不同的数字确实有空格.

解决方案

Alphanum 算法

来自网站

人们用数字对字符串进行排序与​​软件不同.大多数排序算法比较 ASCII 值,这会产生与人类逻辑不一致的排序.以下是解决方法."

这是该站点上 Java 比较器实现的链接.>

I need to write a Java Comparator class that compares Strings, however with one twist. If the two strings it is comparing are the same at the beginning and end of the string are the same, and the middle part that differs is an integer, then compare based on the numeric values of those integers. For example, I want the following strings to end up in order they're shown:

  • aaa
  • bbb 3 ccc
  • bbb 12 ccc
  • ccc 11
  • ddd
  • eee 3 ddd jpeg2000 eee
  • eee 12 ddd jpeg2000 eee

As you can see, there might be other integers in the string, so I can't just use regular expressions to break out any integer. I'm thinking of just walking the strings from the beginning until I find a bit that doesn't match, then walking in from the end until I find a bit that doesn't match, and then comparing the bit in the middle to the regular expression "[0-9]+", and if it compares, then doing a numeric comparison, otherwise doing a lexical comparison.

Is there a better way?

Update I don't think I can guarantee that the other numbers in the string, the ones that may match, don't have spaces around them, or that the ones that differ do have spaces.

解决方案

The Alphanum Algorithm

From the website

"People sort strings with numbers differently than software. Most sorting algorithms compare ASCII values, which produces an ordering that is inconsistent with human logic. Here's how to fix it."

Edit: Here's a link to the Java Comparator Implementation from that site.

这篇关于对可能包含数字的字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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