我需要通过字符子串对字符串数组进行排序,如下所示:
[0] = "gtrd3455";
[1] = "wsft885";
[2] = "ltzy96545";
[3] = "scry5558";
[4] = "lopa475";
我需要按以下方式排序“3455,885,96545,5558,475” 我需要对数组的前4个字符进行子串,对其进行排序并在数组中显示,如下面的输出。
输出应该是一个数组:
[0] = "ltzy96545";
[1] = "scry5558";
[2] = "gtrd3455";
[3] = "wsft885";
[4] = "lopa475";
我如何在Java中执行此操作的示例?
答案 0 :(得分:7)
您可以使用Comparator
并使用Array#sort
方法根据需要对其进行排序: -
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));
输出: -
[ltzy96545, gtrd3455, lopa475]