user1420042
user1420042

Reputation: 1709

How can I sort a string with integers in Java?

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?

Upvotes: 2

Views: 2400

Answers (5)

Andrej
Andrej

Reputation: 1736

When sorting numerically convert strings to numbers before comparing them.

Upvotes: 0

nd.
nd.

Reputation: 8932

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?

Upvotes: 1

Kanagaraj M
Kanagaraj M

Reputation: 966

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

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.

Upvotes: 2

Vallabh Patade
Vallabh Patade

Reputation: 5110

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

Upvotes: 2

Related Questions