public class WrapperTest {
/**
* 对一串字符串进行从小打到的排序
* "20 78 9 -7 88 36 29"
*/
private static final String space_sepa=" ";
public static void main(String[] args) {
String s="20 78 9 -7 88 36 29";
//将字符串变成字符型的数组(分成子串)
String[] arr=stringToArray(s);
//将字符型数组变成int型数组
int[] arr_num=charToInt(arr);
//将int型数组进行排序
arr_num=selectArray(arr_num);
//排序后,将int数组变成字符串
s=toStringMehtod(arr_num);
System.out.println(s);
}
private static String toStringMehtod(int[] arr_num) {
StringBuilder sb=new StringBuilder();
for (int i = 0; i < arr_num.length; i++) {
sb.append(arr_num[i]+space_sepa);
}
return sb.toString();
}
private static int[] selectArray(int[] arr_num) {
for (int i = 0; i < arr_num.length-1; i++) {
for (int j = i+1; j < arr_num.length; j++) {
if (arr_num[i]>arr_num[j]) {
swap(arr_num, i, j);
}
}
}
return arr_num;
}
private static void swap(int[] arr, int i, int j) {
int temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
private static int[] charToInt(String[] arr) {
int[] arr_num=new int[arr.length];
for (int i = 0; i < arr.length; i++) {
arr_num[i]=Integer.parseInt(arr[i]);
}
return arr_num;
}
private static String[] stringToArray(String s) {
String[] arr=s.split(space_sepa);
return arr;
}
}
将一串字符串进行从小到大排序
最新推荐文章于 2023-10-16 14:02:23 发布