实现Linux下Sort -t : -k 2的功能
Sort -t : -k 2
:即要求以冒号作为分隔符,给定数据的第二个区域的升序排列为标准,对输入数据进行排序。import java.util.*;
public class MySort {
public static void main(String[] args) {
int field = Integer.parseInt(args[0])-1;
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);
}
Arrays.sort(toSort);
System.out.println("After sort:");
for (String str : toSort) {
System.out.println(str);
}
}
}
伪代码:
产品代码:对关键代码解释在注释中均已给出,这里就不作重复说明
import java.util.*;
public class MySort {
public static void main(String[] args) {
int field = Integer.parseInt(args[0])-1;
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);
}
int[] k3 = new int[toSort.length];
for (int i = 0; i < toSort.length; i++) {//遍历toSort这个数组,将每个字符串按照冒号进行分隔,分隔后得到的字符串保留在tmp中
String[] tmp = toSort[i].split(":");
k3[i] = Integer.parseInt(tmp[field]);//求field的所对应的值
}
Arrays.sort(k3);//对k3进行升序排列,要求按照第二个field进行排序,所以上面k3应该保留的是第二个field的值
System.out.println("After sort:");
//Arrays.sort(k3);
for (int i = 0; i < k3.length; i++) {//升序输出以field为关键字的toSort排序,所以下面就是寻找k3[i]相等的关键字所在的字符串位置
for (int j = 0; j < toSort.length; j++){
if (k3[i] ==Integer.parseInt((toSort[j].split(":"))[field])) {//当k3[i]等于temp[field]里面的数值时,输出,
// 但是由于temp是一个一直变化的,所以只能重新进行temp数组的生成过程
System.out.println(toSort[j]);
}
}
}
}
}
测试代码:我是直接将主类改成单元,然后调用该单元对其进行测试
public class testMysort {
public static void main(String[] args) {
mysort3 sort1 = new mysort3();
String[] toSort = {"aaa:10:1:1",
"ccc:30:3:4",
"bbb:50:4:5",
"ddd:20:5:3",
"eee:40:2:20"};
sort1.mySort(toSort,1);
System.out.println();
sort1.mySort(toSort,3);
System.out.println();
}
}
学号20175313 《实现Linux下Sort -t : -k 2功能》第十二周
原文:https://www.cnblogs.com/xiannvyeye/p/10883003.html