排序上的字符串,可以包含若干 [英] Sort on a string that may contain a number

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

问题描述

我需要编写比较字符串,但是有一个扭曲一个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
  • 在电子电气设备12 DDD JPEG2000 EEE

正如你所看到的,有可能是在字符串中的其它整数,所以我不能只是使用普通的EX pressions打出来的任意整数。我想只是走弦从一开始,直到我发现了一点不匹配,那么走在从底部直到我觉得有点不匹配,然后在比较中间位到常规的前pression[0-9] +,如果它比较,然后做一个数字比较,否则做一个词汇比较。

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.

有没有更好的办法?

更新我不认为我可以保证,在字符串中的其他数字,那些可以匹配,没有他们周围的空间,或者说,那些不同的是有空间

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.

推荐答案

的Alphanum算法

从网站

的人分开,用数字的字符串比软件不同,大多数排序算法比较ASCII值,产生一个顺序,它与人类的逻辑不一致。这里是如何解决它。

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

编辑:下面是该网站的链接的Java比较实施

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

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

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