- package com.string.demo;
- import java.util.Arrays;
- public class StringDemo2 {
- /**
- * 3.3 练习3:对字符串按照指定的内容切割,然后排序,输出排序后的字符串
- * 思路:
- 第一步:对字符串进行切割, 使用字符串数组保存切割后的字符串
- 第二步:对字符串数组进行排序 (java.util.Arrays.sort(字符串数组))
-
- 第三步:遍历排序后的字符串数组,把数组中存储的字符串再次拼接为一个字符串
- 定义一个字符串,用来保存从数组中获取的每一个字符串
- 把数组中存储的每一个字符串,获取到和定义的字符串进行拼接
- 提示:在拼接字符串时需要有之前的分隔符
-
- 最后,输出拼接后的字符串
- */
- public static void main(String [] args) {
-
- String str ="NBA-CBA-kebo-james-Jordan";
- //使用“-”对字符串进行切割
- String[] toStr = str.split("-"); //对字符串进行利用”,“切割,用string数组strs接收
- //排序
- Arrays.sort(toStr);
- //数组中存储的字符串再次拼接为一个字符串
- String temp = Arrays.toString(toStr);
- //打印字符数组转换为字符串后的新字符串
- System.out.println(temp);
- //数组中有“,”,需要被替换为“-”
- temp = temp.replace(',', '-');
- //再次数次替换后的字符串
- System.out.println(temp);
- //对字符串两边的中括号截取掉
- str = temp.substring(1, temp.length()-1);
- //输出截取后的字符串
- System.out.println(str);
- }
- }
复制代码 |
|