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

Lea*_*ava 0 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在努力与内循环.

目前我的输出如下:

AClasspClasspClasslClasseClass
Run Code Online (Sandbox Code Playgroud)

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

acplpalses
Run Code Online (Sandbox Code Playgroud)

扩展问题:

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

目前的尝试:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,这只是输出如上所述,只是以"Apple"的相反顺序输出,格式与上一个相同:

eclasslclasspclasspclassaclass
Run Code Online (Sandbox Code Playgroud)

azr*_*zro 5

您不需要2个循环,因为您对两者都采取相同的指示 Strings


同一订单:

  1. 简单相同尺寸的案例:

    for (int i = 0; i < a.length(); i++) {
        System.out.print(a.charAt(i));
        System.out.print(b.charAt(i));
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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
    
    Run Code Online (Sandbox Code Playgroud)

不同的顺序:

  1. 简单相同尺寸的案例:

    for (int i = 0; i < a.length(); i++) {
        System.out.print(a.charAt(i));
        System.out.print(b.charAt(b.length() - i - 1));
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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));
    
    Run Code Online (Sandbox Code Playgroud)