嵌套的for循环在两个字符串之间进行迭代

时间:2018-11-11 23:19:11

标签: java loops for-loop nested-loops

我想使用for循环,遍历每个字符串并依次输出每个字符。

String a = "apple";
String b = "class";

for (int i = 0;  i < a.length() ; i++) { // - 1 because 0 = 1
    System.out.print(a.charAt(i));
    for (int j = 0; j < b.length(); j ++) {
        System.out.print(b.charAt(j));
    }
}

我正在为内部循环而苦恼。

此刻,我的输出如下:

AClasspClasspClasslClasseClass

但是,我想实现以下目标:

acplpalses

扩展问题:

如何反向输出一个字符串而正常输出另一个字符串呢?

当前尝试:

for (int i = a.length() - 1; i >= 0; i--) {
    System.out.println(a.charAt(i));
    for (int j = 0; j < b.length(); j ++) {
        System.out.println(b.charAt(j));
    }
}

但是,这只是按照上面的格式输出,只是带有相反顺序的“ Apple”输出:

eclasslclasspclasspclassaclass

3 个答案:

答案 0 :(得分:5)

您不需要两个循环,因为两个Strings都使用相同的索引


相同顺序:

  1. 相同尺寸的简易表壳

    for (int i = 0; i < a.length(); i++) {
        System.out.print(a.charAt(i));
        System.out.print(b.charAt(i));
    }
    
  2. 复杂不同尺寸的保护套

    int minLength = Math.min(a.length(), b.length());
    for (int i = 0; i < minLength; i++) {
        System.out.print(a.charAt(i));
        System.out.print(b.charAt(i));
    }
    System.out.print(a.substring(minLength)); // prints the remaining if 'a' is longer
    System.out.print(b.substring(minLength)); // prints the remaining if 'b' is longer
    

不同订单:

  1. 相同尺寸的简易表壳

    for (int i = 0; i < a.length(); i++) {
        System.out.print(a.charAt(i));
        System.out.print(b.charAt(b.length() - i - 1));
    }
    
  2. 复杂不同尺寸的保护套

    int minLength = Math.min(a.length(), b.length());
    for (int i = 0; i < minLength; i++) {
        System.out.print(a.charAt(i));
        System.out.print(b.charAt(b.length() - i - 1));
    }
    System.out.print(a.substring(minLength));
    System.out.print(new StringBuilder(b).reverse().substring(minLength));
    

答案 1 :(得分:2)

使用Java 8流的另一种解决方案:

System.out.println(
    IntStream.range(0, Math.min(a.length(), b.length()))
        .mapToObj(i -> "" + a.charAt(i) + b.charAt(i))
        .collect(Collectors.joining(""))
);

答案 2 :(得分:1)

对于扩展问题- 假设两个字符串的大小相同

for (int i = 0; i < a.length(); i++) {
    System.out.print(a.charAt(a.length()-1-i));
    System.out.print(b.charAt(i));
}