3 回答
TA贡献1876条经验 获得超7个赞
您不需要 2 个循环,因为您对两者都采用相同的索引 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));
TA贡献1802条经验 获得超4个赞
另一个使用 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(""))
);
TA贡献1806条经验 获得超5个赞
对于扩展问题-假设两个字符串的大小相同
for (int i = 0; i < a.length(); i++) {
System.out.print(a.charAt(a.length()-1-i));
System.out.print(b.charAt(i));
}
添加回答
举报