如何在Java中使用整数对字符串排序? [英] How can I sort a string with integers in Java?

查看:145
本文介绍了如何在Java中使用整数对字符串排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组.我数组中的每个空格都包含两个字符串(一个字符串仅包含字母,另外一个数字).

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

我现在想做的是按字母顺序或数字顺序对数组进行排序(取决于在数组中选择的空间).为此,我正在使用compareTo()方法.但是,我发现当我尝试根据数字对数组进行排序时,它实际上并没有真正起作用.

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.

我的猜测是,由于Java使用ascii代码处理字符串,所以数字不会按数字顺序显示.

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?

推荐答案

在您的compareTo()方法中,当您检测到正在查看表示整数的两个字符串时,请确保它们的长度相同,然后再进行比较.如果一个字符串较短,则在其前添加零,直到长度相等为止.

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.

例如,32123过去常常无法与默认算法正确比较:3更大,因此32比较为在132之后.但是,一旦添加零,该比较将再次起作用:032小于123.

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.

这篇关于如何在Java中使用整数对字符串排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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