0
点赞
收藏
分享

微信扫一扫

插入指定字符排序输出


将一组乱序的字符进行排序,使其变成有序(假设有8个字符并都不相同),然后任意输入一个字符,按字母顺序找到其合适的位置插入到字符序列中。
System.out.println(“请输入要插入的字符:”);

char num=input.next().charAt(0);

如:原始字符序列位O T Y A E V B Z,首先排序输出A B E O T V Y Z,然后输入K,找到K所在的位置并插入,最终结果为 A B E K O T V Y Z

public static void main(String[] args) {
    test("helloWorld", 'z');
    test("HiDani", 'a');
    test("compile", 'h');
}

public static void test(String s, char c) {
    char[] arr = s.toCharArray();
    for (int i = 0; i < arr.length; i++) {
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[i] > arr[j]) {
                char temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    String b = new String(arr);
    System.out.println("对字符串排序后:" + b);
    StringBuilder sb = new StringBuilder(b);
    if (c <= b.charAt(0)) {
        sb.insert(0, c);
    } else if (c >= b.charAt(b.length() - 1)) {
        sb.insert(b.length(), c);
    } else {
        for (int i = 0; i < b.length() - 1; i++) {
            if (c > b.charAt(i) && c < b.charAt(i + 1)) {
                sb.insert(i + 1, c);
                break;
            }
        }
    }
    System.out.printf("插入字符串%c后:%s%n", c, sb);
}

  • 运行结果

对字符串排序后:Wdehllloor
插入字符串z后:Wdehllloorz
对字符串排序后:DHaiin
插入字符串a后:DHaiin
对字符串排序后:ceilmop
插入字符串h后:cehilmop


举报

相关推荐

0 条评论