1

如何在java中混合两个字符串?

如果我有abcdeand 123456789,最简单的方法是什么a1b2c3d4e56789

这是我的代码:

public class Mix {
    public static void main(String[] args) {
        String s1="vera", s2="ronaldo"; /* input strings */

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < s1.length(); i++) {
            sb.append(s1.charAt(i));
            sb.append(s2.charAt(i));
        }

        String result = sb.toString();
        System.out.println(result);
    }
}

输出:

vreornaa

我的预期输出:

vreornaaldo
4

2 回答 2

2

为了补充@Rohit,您还应该检查两个字符串中哪个长度更长,并将其附加到结果中。

String s1 = "vera", s2 = "ronaldo";
StringBuilder sb = new StringBuilder();

int minLength = Math.min(s1.length(), s2.length());
for (int i = 0; i < minLength; i++){
    sb.append(s1.charAt(i));
    sb.append(s2.charAt(i));
}

for (int i = minLength; i < s1.length(); i++){
    sb.append(s1.charAt(i));
}

for (int i = minLength; i < s2.length(); i++){
    sb.append(s2.charAt(i));
}

System.out.println(sb.toString());
于 2013-09-16T17:17:36.130 回答
2

你快到了。您只需要添加另一个 for 循环来附加较大字符串的剩余部分。只需将第二个循环从较小的字符串长度迭代到较大的字符串长度:

for (int i = s1.length(); i < s2.length(); ++i) {
    sb.append(s2.charAt(i));
}
于 2013-09-16T17:09:30.557 回答