1 import java.util.Iterator;
2 import java.util.TreeSet;
3
4 /*
5 需求:将字符串中的数值进行排序。
6 例如String str = "2 8 5 10 12 4"; ----> "2 4 5 8 10 12 "
7 */
8
9 public class Demo7 {
10 public static void main(String[] args) {
11 String str = "2 8 5 10 12 4";
12 //用split方法,切割空格,保存到 字符串 数组中
13 //不要转换成 字符 数组,否则10和12会被拆分成1、0和1、2
14 String[] newStr = str.split(" ");
15 TreeSet tree = new TreeSet();
16 for (int j = 0; j < newStr.length; j++) {
17 tree.add(Integer.parseInt(newStr[j]));//利用 Integer.parseInt()将字符串数据转成int型数据
18 }
19
20 //注意:set接口是没有get()方法的,只有list有,所以这里需要使用迭代器
21 Iterator it = tree.iterator();
22 while (it.hasNext()) {
23 System.out.print(it.next() + " ");
24 }
25 }
26 }