How to sort Alphanumeric String

前端 未结 11 1424
我寻月下人不归
我寻月下人不归 2020-12-10 06:25

I have a problem with sorting strings which include integers. If I use the below code I get sorting like: 1some, 2some, 20some, 21some, 3some, some

However I want it

相关标签:
11条回答
  • 2020-12-10 07:04

    You need to implement your own Comparator to do this kind of custom sorting. The default String.compareTo() method seems to sort numbers before characters. When 0 in 20some gets compared to s in 3some the 0 has a higher sort priority and therefore the whole word gets sorted in first.
    What you would need to do is this: try to split you strings into the number and the character part. That's a hard task since those Strings can consist of many of those parts (or don't they?). You may use algorithms like Alphanum, which Murtaza already showed to you.
    If you want to implement it yourself, you could check, where the number part ends. Then parse it to an int with Integer.parse(). Compare int parts if they exist in both Strings, then compare the rest. Well that may not be the most professional solution, but as a beginner you may want craft those things yourself to learn it.

    0 讨论(0)
  • 2020-12-10 07:06

    You can't use the default String compareTo() instead need compare the Strings following the below algorithm.

    1. Loop through the first and second String character by character and get a chunk of all strings or numbers
    2. Check if the chunks are numbers or strings
    3. If numbers sort numerically else use String compareTo()

    Repeat the steps.

    0 讨论(0)
  • 2020-12-10 07:11

    You can do the core of it in one line using regex to extract the numeric part:

    Collections.sort(selectedNodes, new Comparator<DefaultMutableTreeNode>() {
        @Override
        public int compare(DefaultMutableTreeNode o1,
            DefaultMutableTreeNode o2) {
            return Integer.parseInt(o1.getUserObject().toString().replaceAll("\\D", "")) -
                Integer.parseInt(o2.getUserObject().toString().replaceAll("\\D", ""));
        }
    });
    
    0 讨论(0)
  • 2020-12-10 07:12

    If you know that pattern is always NUMALPHA or ALPHANUM and alpha always same:

    if(str1.length() != str2.length()){
       return str1.length() - str2.length();
    }
    
    return str1.compareTo(str2);
    
    0 讨论(0)
  • 2020-12-10 07:15
        String [] str = new String[]{"1some", "2some", "20some", "21some", "3some", "some"};
        List<String> list = Arrays.asList(str);
    
        Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
        System.out.println(list);
    
    0 讨论(0)
提交回复
热议问题