Java 练习题02 (包装类 (对字符串进行排序))
有一个字符串“101,87,88,87,98”对数字由小到大排序。
import java.util.Arrays; public class Demo01 { public static void main(String[] args) { String spa = "101,87,88,87,98"; //1.分割每个数字 String[] str = spa.split(","); //2.定义int类型数组保存结果 int[] arr = new int[str.length]; //3.通过遍历将字符串转为integer类型 for (int i = 0; i < str.length; i++) { int num = Integer.parseInt(str[i]); arr[i] = num; } //4.将数组排序 for (int i = 0; i < arr.length-1; i++) { for (int j = 0; j < arr.length-1-i; j++) { if(arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } //5.使用StringBuilder类对多个字符串进行拼接 StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(arr[i]); if(i != arr.length-1) {//如果下标不为最大时,需要添加, sb.append(","); } } System.out.println(sb.toString()); //87,87,88,98,101 } }