字符串排序简单的工具类,数组转list,list转数组

   public static void main(String[] args) {
/* String[] str = {"a", "c", "b", "x", "y", "z", "j", "h", "n", "m", "q"};*/
/* printArr(str);
ArraySort(str, 1); //练习排序方法
// Arrays.sort(str); 排序用法
printArr(str);*/ /* List <String> srtList = Arrays.asList("a", "c", "b", "x", "y", "z", "j", "h", "n", "m", "q");
;
//printList(arrToList(str));
*//*ListToArr(srtList);*//*
printArr(ListToArr(srtList));*/ String str = "asdfghjklmnbvcxzqwertyuiop";
System.out.println(str); str = StringSort(str, 1);
System.out.println(str);
} /**
*
* @param str 排序字符串
* @param sortType 排序规则,0--从小到大,1--从大到小
* @return
*/
public static String StringSort(String str, int sortType) { char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
for (int j = i + 1; j < ch.length; j++) {
String stri = String.valueOf(ch[i]);
String strj = String.valueOf(ch[j]);
if (sortType == 0) {
if (stri.compareTo(strj) > 0) {
chaSwap(ch, i, j);
}
} else {
if (stri.compareTo(strj) < 0) {
chaSwap(ch, i, j);
}
}
} } str = "";
for (int i = 0; i < ch.length; i++) {
str += String.valueOf(ch[i]);
} return str;
} public static void chaSwap(char[] ch, int x, int y) { char temp = ch[x];
ch[x] = ch[y];
ch[y] = temp;
} /**
* @param arr 排序数组
* @param SortType 排序规则,0---从小到大,1从大到小
* @return
*/
public static String[] ArraySort(String[] arr, int SortType) { if (arr == null)
return null; if (null != arr && arr.length > 0) {
int len = arr.length; for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) { if (SortType == 0) {//从小到大排序
if (arr[i].compareTo(arr[j]) > 0) {
swap(arr, i, j);
}
} else { if (arr[i].compareTo(arr[j]) < 0) {
swap(arr, i, j);
}
}
} } }
return arr;
} /**
* 交换两个元素的位置的方法
*
* @param arr 需要交换元素的数组
* @param x 索引i
* @param y 索引j
*/
public static void swap(String[] arr, int x, int y) { String temp = arr[x];
arr[x] = arr[y];
arr[y] = temp; } /**
* 打印字符串数组
*
* @param str
*/
private static void printArr(String[] str) {
for (int i = 0; i < str.length; i++) {
System.out.print(str[i] + "\t");
}
System.out.println();
} public static List <Object> arrToList(Object arr[]) {
return Arrays.asList(arr);
} private static void printList(List <Object> list) { for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + "\t");
}
System.out.println();
} public static String[] ListToArr(List <String> list) { return (String[]) list.toArray(); }
上一篇:mysql int(3)与int(11)的区别


下一篇:移植QT到ZedBoard(制作运行库镜像) 交叉编译 分类: ubuntu shell ZedBoard OpenCV 2014-11-08 18:49 219人阅读 评论(0) 收藏