我想获取两个字符串并使用 for 方法将字符交替为一个新字符串。
示例:“二”和“一”
结果:“townoe”
这就是我目前所拥有的,我真的不知道如何完成它。
public class Alternator {
String alternate(String a, String b) {
String s = "";
for (int i = 0; i < a.length(); i++) {
s += i;
System.out.println(s);
}
return null;
}
}
最佳答案
public class Alternator{
public static String alternate(String a, String b){
String s = "";
int i = 0;
while (i < a.length() && i < b.length()){
s += a.charAt(i) +""+ b.charAt(i);
i++;
}
while (i < a.length() ){
s += a.charAt(i);
i++;
}
while (i < b.length()){
s += b.charAt(i);
i++;
}
return s;
}
public static void main(String[] args){
String a = "two", b = "one";
String s = Alternator.alternate(a,b);
System.out.println(s);
}
}
要使用 for 循环而不是 while 循环,只需删除所有带有 for 行的 while 行,如下所示,然后从每个 while 循环中删除 i++ 行
for(; i < a.length() && i < b.length(); i++){
//the inside of the loop MINUS THE LINE i++
}
for(; i < a.length(); i++){
//the inside of the loop MINUS THE LINE i++
}
for(; i < b.length(); i++){
//the inside of the loop MINUS THE LINE i++
}
关于java - 两个不同输入的交替字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25954495/