How can I sort a string with integers in Java?

丶灬走出姿态 提交于 2020-05-23 10:36:31

问题


I have got an array. Each space in my array holds two strings (one string contains just letters, the other one numbers).

What I am trying to do now is to sort the array either alphabetically or numerically (depending on which space in the array is chosen). To do that, I am using the compareTo() method. However, I found that when I try to sort the array according to the numbers, it actually does not really work.

My guess is, that since Java handles strings with the ascii codes, numbers don't show up in numerical order.

Question: How can I fix that?


回答1:


In your compareTo() method, when you detect that you are looking at two strings representing integers, make sure they are the same length before comparing them. If one string is shorter, prepend leading zeros to it until the strings are of equal length.

For example, 32 and 123 used to not compare correctly with the default algorithm: 3 is greater, so 32 compares as being after 132. However, once you prepend zero, the comparison works again: 032 is less than 123.




回答2:


For comparing Numbers, may be this will helpful.

The Alphanum Algorithm

From the website : http://www.davekoelle.com/alphanum.html

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.

Here's a link to the Java Comparator Implementation from that site. http://www.davekoelle.com/files/AlphanumComparator.java




回答3:


Yes you are correct, Strings are sorted according to their Unicode codepoint value. This means that "2" is smaller than "a" and larger than "11".

I suspect that you are looking for a Natural Sort Order. A great SO post detailling about it is Java String Number Comparator and you can find actual implementations in the SO post Natural sort order string comparison in Java - is one built in?




回答4:


You can use Long(or)Folat.isNaN() method to check its number or sting then by using that you can do your sorting.




回答5:


When sorting numerically convert strings to numbers before comparing them.



来源:https://stackoverflow.com/questions/14277004/how-can-i-sort-a-string-with-integers-in-java

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