在Java中逐字合并两个字符串? [英] Merge two strings letter by letter in Java?

查看:727
本文介绍了在Java中逐字合并两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


给定两个字符串A和B,创建一个更大的字符串,由A的第一个字符组成,B的第一个字符,A的第二个字符,B的第二个字符,等等上。任何剩余的字符都会在结果的末尾出现。

Given two strings, A and B, create a bigger string made of the first char of A, the first char of B, the second char of A, the second char of B, and so on. Any leftover chars go at the end of the result.



public String mixString(String a, String b)
{


    String str = "";
    int len = 0;

    if (a.length() >= b.length())
    {
        len = a.length();
    } else
        len = b.length();

    for (int i = 0; i < len; i++)
    {

        if (i < a.length())
        {
            str += a.charAt(i);
        }

        if (i < b.length())
        {
            str += b.charAt(i);
        }

    }
    return str;
}


推荐答案

你有一个可行的方法,但你可以通过使用一个带有两个计数器的循环来显着简化它:

You've got a workable approach, but you could significantly simplify it by using a single loop with two counters:

int apos = 0, bpos = 0;
while (apos != a.length() || bpos != b.length()) {
    if (apos < a.length()) m += a.charAt(apos++);
    if (bpos < b.length()) m += b.charAt(bpos++);
}

在此循环中,您将通过提前<$在每一步取得进步 c $ c>次, bpos ,或两者兼而有之。一旦字符串用完了字符,其相应的 pos 就会停止前进。当 pos 达到目的时,循环结束。

In this loop you will "make progress" on each step by advancing apos, bpos, or both. Once a string runs out of characters, its corresponding pos stops advancing. The loop is over when both pos reach their ends.

注意:当你需要附加到字符串中时循环,使用 StringBuilder

Note: When you need to append to a string in a loop, use StringBuilder.

这篇关于在Java中逐字合并两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆