简体   繁体   English

如何根据解析的第一个数字对字符串数组进行排序

[英]How to sort an array of Strings based on the parsed first digit

I just finished a coding competition where one of the problems required me to sort an array of strings, but numerically based on the number that appeared first in the string.我刚刚完成了一场编码竞赛,其中一个问题要求我对字符串数组进行排序,但数字是基于字符串中第一个出现的数字。 for example:例如:

String[] array = 
{{"18.sdfahsdfkjadf"},
 {"1.skjfhadksfhad"},
 {"2.asldfalsdf"}};

would need to be sorted as 1.sk... first, 2.as..., and then 18.sd... last.需要排序为 1.sk... 首先,2.as...,然后是 18.sd... 最后。 But if you use (in Java) Arrays.sort(array), it would be ordered as 1, 18, then 2 because its going off the the first char first and not as a number.但是,如果您使用(在 Java 中)Arrays.sort(array),它将被排序为 1、18,然后是 2,因为它首先离开第一个字符而不是数字。

You can split each string on \D (which means non-digit) and compare the strings based on the first elements, parsed into an integer, of the resulting arrays.您可以在\D上拆分每个字符串(这意味着非数字)并根据第一个元素比较字符串,解析为 integer,生成 arrays。

Demo:演示:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        String[] array = { "18.sdfahsdfkjadf", "1.skjfhadksfhad", "2.asldfalsdf" };
        
        Arrays.sort(array, 
                        (s1, s2) -> 
                            Integer.compare(
                                                Integer.parseInt(s1.split("\\D")[0]),
                                                Integer.parseInt(s2.split("\\D")[0])
                                            )
                    );

        System.out.println(Arrays.toString(array));
    }
}

Output: Output:

[1.skjfhadksfhad, 2.asldfalsdf, 18.sdfahsdfkjadf]

Using the Streams API, you could produce something like this (assuming the numbers are always separated from the rest by punctuation):使用Streams API,您可以生成类似这样的结果(假设数字始终通过标点符号与 rest 分开):

List<String> sorted = Arrays.stream(array).sorted((s1, s2) -> {
         Integer i = Integer.parseInt(s1.split("\\.")[0]);
         Integer j = Integer.parseInt(s2.split("\\.")[0]);
         return i.compareTo(j);
}).collect(Collectors.toList());

With the resulting array being: [1.skjfhadksfhad, 2.asldfalsdf, 18.sdfahsdfkjadf]结果数组为: [1.skjfhadksfhad, 2.asldfalsdf, 18.sdfahsdfkjadf]

Try this.尝试这个。

Arrays.sort(array, Comparator.comparingInt(s -> Integer.parseInt(s.split("\\.")[0])));
System.out.println(Arrays.toString(array));

output: output:

[1.skjfhadksfhad, 2.asldfalsdf, 18.sdfahsdfkjadf]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM