Java sorting an String Array by a Substring of characters

后端 未结 1 1196
半阙折子戏
半阙折子戏 2020-12-18 12:50

I need to sort an array of strings like the following, by a substring of characters:

[0] = \"gtrd3455\";
[1] = \"wsft885\";
[2] = \"ltzy96545\";
[3] = \"scry         


        
相关标签:
1条回答
  • 2020-12-18 13:36

    You can use a Comparator, and use Array#sort method with it, to sort it according to your need: -

    String[] yourArray = new String[3];
    yourArray[0] = "gtrd3455";
    yourArray[1] = "ltzy96545";
    yourArray[2] = "lopa475";
    
    Arrays.sort(yourArray, new Comparator<String>() {
        public int compare(String str1, String str2) {
            String substr1 = str1.substring(4);
            String substr2 = str2.substring(4);
    
            return Integer.valueOf(substr2).compareTo(Integer.valueOf(substr1));
        }
    });
    
    System.out.println(Arrays.toString(yourArray));
    

    OUTPUT: -

    [ltzy96545, gtrd3455, lopa475]
    
    0 讨论(0)
提交回复
热议问题