字符串排序程序,对一个字符串中的数值进行从小到大的排序
例如排序前给定的字符串为" 20 78 9 -7 88 36 29"
排序后: -7 9 20 29 36 78 88
要求使用包装类对数值类型的字符串转换成整型进行排序。

java
public class StringSort {
public static void main(String[] args) {
String str = "20 78 9 -7 88 36 29";
//将字符串 转化为Int类型 并存入int数组
int[] strArr = strChange(str);
//排序
strSort(strArr);
//输出
printArray(strArr);
}
//字符串 转 int
public static int[] strChange(String s){
//观察数据可知,可用spilt方法,以空格为分隔符,将字符串分隔开,并存入String数组
String[] spiltStr = s.split(" ");
//创建新数组,用于存放转化为int后的数据
int[] strInt= new int[spiltStr.length];
for (int i = 0; i < spiltStr.length; i++) {
//调用Integer类的parseInt方法,将String类型转化为Int类型
strInt[i] = Integer.parseInt(spiltStr[i]);
}
return strInt;
}
//选择排序法
public static void strSort(int[] arr){
for (int i = 0; i < arr.length; i++) {
int k=i;
for (int j = i+1; j <arr.length ; j++) {
if (arr[k]>arr[j]){
k = j;
}
}
int temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
}
//打印数组函数
public static void printArray(int[] arr){
for (int i=0;i<arr.length;i++) {
if (i==0){
if (arr.length==1){
System.out.println("["+arr[0]+"]");
}else{
System.out.print("["+arr[i]+",");
}
}else if(i==arr.length-1){
System.out.println(arr[i]+"]");
}else {
System.out.print(arr[i]+",");
}
}
System.out.println("--------------------------------------------------------");
}
}
