Java一个小练习
把字符串str分割程String数组,然后转换成int数组,排序
String str = "123 345 89 93 2 6573 223"
然后在拼接成一个字符串如下:
"2 89 93 123 223 345 6573"
/*** String str = "123 345 89 93 2 6573 223"* 把字符串str分割程String数组,然后转换成int数组,排序* 然后在拼接成一个字符串如下:* "2 89 93 123 223 345 6573"*/
public class StringToInt {public static void main(String[] args) {String str = "123 345 89 93 2 6573 223";//输出原字符串System.out.println("str1 = "+str);//分割字符串给赋给arr数组String[] arr = str.split(" ");//输出arr数组System.out.print("arr = ");for (int i = 0; i < arr.length; i++) {System.out.print(arr[i]+"\t");}System.out.println();int []arrInt = new int[str.length()];//String转intfor (int i = 0; i < arr.length; i++) {arrInt[i] = Integer.parseInt(arr[i]);}//遍历int数组System.out.print("arrInt = ");for (int i = 0; i < arr.length; i++) {System.out.print(arrInt[i]+"\t");}System.out.println();//排序for (int i = 0; i < arr.length-1; i++) {for (int j = 0; j < arr.length-1-i; j++) {int arr1;if (arrInt[j]>arrInt[j+1]){arr1 = arrInt[j];arrInt[j] = arrInt[j+1];arrInt[j+1] = arr1;}}}System.out.print("排好序的新数组 = ");for (int i = 0; i < arr.length; i++) {System.out.print(arrInt[i]+"\t");}System.out.println();//int数组转换StringStringBuffer sb = new StringBuffer();for (int i = 0; i < arr.length; i++) {sb.append(arrInt[i]+" ");}System.out.print("sb = "+sb);}
}
运行结果如下: