研究sort的其餘功能,要能改的動代碼,模擬實現Linux下Sort -t : -k 2的功能。java
/** * Created by xiang on 2018/5/17. */ import java.util.*; public class MySort { public static void main(String[] args) { String[] toSort = {"aaa:10:1:1", "ccc:30:3:4", "bbb:50:4:5", "ddd:20:5:3", "eee:40:2:20"}; System.out.println("Before sort:"); for (String str : toSort) System.out.println(str); System.out.println("After sort:"); int[] s = new int[toSort.length]; String[][] string = new String [toSort.length][4]; for (int i = 0; i < toSort.length; i++) { string[i] = toSort[i].split(":"); s[i] = Integer.parseInt(string[i][1]); } Arrays.sort(s); for (int i = 0; i < s.length; i++) { for (int j = 0; j < toSort.length; j++) { if(s[i] == Integer.parseInt(string[j][1])){ System.out.println(toSort[j]); } } } } }
sort實驗中最關鍵的是string[i] = toSort[i].split(":"); s[i] = Integer.parseInt(string[i][1]);
用冒號做爲間隔符,並針對第二列來進行數值升序排序。測試