按字符串中的值对字符串数组进行排序

时间:2014-09-04 04:44:08

标签: java arrays string sorting int

我已经被这一段时间困扰了一段时间。我有一个字符串数组,所有字符串都包含一些我需要提取的数值,并用于比较以排序数组。我已经尝试使用内置方法排序与比较器,但没有成功。

如果有人能给我一点见解或指出我正确的方向,我将不胜感激。

数组包含以下格式的字符串:" NAME已工作x小时"

我的意图是将数字拉出来并根据整数的值进行排序,同时仍保持与名称的关系。

public static <T> void sort(T[] a, Comparator<? super T> c)

3 个答案:

答案 0 :(得分:2)

您可以使用Collections.sort使用comparator对字符串进行排序,并将String解析为Integer,以便按整数对其进行排序。

<强>样品:

    String s[] = { "10", "2", "1" };
    Collections.sort(Arrays.asList(s), new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            int i = Integer.parseInt(o1);
            int i2 = Integer.parseInt(o2);
            if (i > i2)
                return 1;
            else if (i < i2)
                return -1;
            else
                return 0;
        }
    });
    System.out.println(Arrays.toString(s));

<强>结果:

[1, 2, 10]

答案 1 :(得分:2)

确保您处理所有边缘情况,但以下代码应该适合您。

public class NumericStringComparator implements Comparator<String> {
    @Override
    public int compare(String str1, String str2) {
        Integer num1 = extractNumericValue(str1);
        Integer num2 = extractNumericValue(str2);

        // handle null/error cases

        return num1.compareTo(num2);
    }

    private static Integer extractNumericValue(String str) {
        // extract numeric value however but as an example
        return Integer.parseInt(str);
    }
}

使用此比较器,您可以使用Arrays.sort(..)方法对列表进行排序

String[] array = ...;
Arrays.sort(array, new NumericStringComparator());

答案 2 :(得分:0)

如果每个字符串只包含数字,那么您可以使用ParseInt获取每个字符串的整数值,然后使用常规比较器对它们进行排序。如果字符串包含非数字字符和整数,那么这会使事情变得复杂,并且您可能希望制作一个帮助方法来为您执行脏工作。可能的(虽然效率低下)实现可能看起来像......

public static int getNumbersFromString(String string)
{
    String numbers = "";
    for(int i = 0; i < string.length; i++)
    {
        if((int)(string.charAt(i) >= 48 && (int)(string.charAt(i) <= 57)
            numbers += string.charAt(i);
    }
    int foo = Integer.parseInt(numbers);
    return foo;
}