我想使用 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
最佳答案
您不需要 2 个循环,因为您对两个字符串
采用相同的索引
相同订单:
简单的相同尺寸案例:
for (int i = 0; i < a.length(); i++) { System.out.print(a.charAt(i)); System.out.print(b.charAt(i)); }
复杂不同尺寸的案例:
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
顺序不同:
简单的相同尺寸案例:
for (int i = 0; i < a.length(); i++) { System.out.print(a.charAt(i)); System.out.print(b.charAt(b.length() - i - 1)); }
复杂不同尺寸的案例:
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));
关于java - 嵌套 for 循环在两个字符串之间迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53254227/