我想使用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
最佳答案
您不需要两个循环,因为两个Strings
的索引相同
相同顺序:
简单的相同大小的情况:
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));