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

我想使用 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


慕村9548890
浏览 184回答 3
3回答

幕布斯6054654

您不需要 2 个循环,因为您对两者都采用相同的索引 Strings相同的顺序:简单的同尺寸案例:for (int i = 0; i < a.length(); i++) {&nbsp; &nbsp; System.out.print(a.charAt(i));&nbsp; &nbsp; System.out.print(b.charAt(i));}复杂的不同尺寸案例:int minLength = Math.min(a.length(), b.length());for (int i = 0; i < minLength; i++) {&nbsp; &nbsp; System.out.print(a.charAt(i));&nbsp; &nbsp; System.out.print(b.charAt(i));}System.out.print(a.substring(minLength)); // prints the remaining if 'a' is longerSystem.out.print(b.substring(minLength)); // prints the remaining if 'b' is longer不同的顺序:简单的同尺寸案例:for (int i = 0; i < a.length(); i++) {&nbsp; &nbsp; System.out.print(a.charAt(i));&nbsp; &nbsp; System.out.print(b.charAt(b.length() - i - 1));}复杂的不同尺寸案例:int minLength = Math.min(a.length(), b.length());for (int i = 0; i < minLength; i++) {&nbsp; &nbsp; System.out.print(a.charAt(i));&nbsp; &nbsp; System.out.print(b.charAt(b.length() - i - 1));}System.out.print(a.substring(minLength));System.out.print(new StringBuilder(b).reverse().substring(minLength));

慕虎7371278

另一个使用 Java 8 流的解决方案:System.out.println(&nbsp; &nbsp; IntStream.range(0, Math.min(a.length(), b.length()))&nbsp; &nbsp; &nbsp; &nbsp; .mapToObj(i -> "" + a.charAt(i) + b.charAt(i))&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.joining("")));

忽然笑

对于扩展问题-假设两个字符串的大小相同for (int i = 0; i < a.length(); i++) {&nbsp; &nbsp; System.out.print(a.charAt(a.length()-1-i));&nbsp; &nbsp; System.out.print(b.charAt(i));}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java