java中如何对以数字开头的字符串集合进行排序
天蓬老师
天蓬老师 2017-04-18 10:36:59
0
2
590
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
Ty80

What you said above is correct. The key is to remove the numbers in front of the string. Maybe you are not familiar with regular expressions at the moment, so I will write a simple method to remove the numbers in front of the string:

import java.util.*;

public class Main {

    // 取出字符串前面的数字
    public static String getStartDigits(String str) {
        int len = str.length();
        int stopPos = 0;
        for (int i = 0; i < len; i++) { // 遍历 str 的字符
            char ch = str.charAt(i);
            if (!(ch >= '0' && ch <= '9')) { // 如果当前字符不是数字
                stopPos = i;
                break;
            }
        }
        return str.substring(0, stopPos);
    }

    public static void sortByStartDigits(List<String> list) {
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                int num1 = Integer.parseInt(getStartDigits(s1));
                int num2 = Integer.parseInt(getStartDigits(s2));

                return num1 - num2;
            }
        });
    }

    public static void main(String[] args) throws Exception {
        List<String> list = Arrays.asList(
                "1号摄像机", "10号摄像机", "2号摄像机", "20号摄像机", "30号摄像机", "31号摄像机");
        System.out.println("排序前:");
        System.out.println(list);
        
        sortByStartDigits(list);
        System.out.println("排序后:");
        System.out.println(list);
    }

}

PHPzhong

Just customize oneComparator.

    String[] arr = {"1号","2号","3号","11号","21号","12号","13号","100号"};
    Arrays.sort(arr);
    System.out.println(Arrays.toString(arr));
    List<String> list = Arrays.asList(arr);
    Collections.sort(list,new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return Integer.parseInt(o1.replaceAll("[^0-9]*", "")) - Integer.parseInt(o2.replaceAll("[^0-9]*", ""));
        }
    });
    System.out.println(list);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template