java - 在Java中逐字母合并两个字符串?

标签 java string

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;
}

最佳答案

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

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++);
}

在此循环中,您将通过推进 aposbpos 或两者来“取得进展”。一旦字符串用完字符,其对应的 pos 就会停止前进。当两个 pos 都到达终点时,循环结束。

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

关于java - 在Java中逐字母合并两个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20508997/

相关文章:

java - 如何在运行 Junit 测试用例时创建用户 session

java - 是否有必要以 root 身份运行 jstack -F(在 Linux 上),如果是,为什么?

python - 如何在 Python 中重复字符串中的单个字符

C# - 将 HTML 无序列表转换为 JSON 数组

python - Pandas :Dataframe.replace() 与正则表达式

java - 如何查找 Java String 是否包含 X 或 Y 并包含 Z

java - 将对象传递给另一个 Activity

java - 在 Android 中从第 0 行 col -1 获取字段槽失败

c++ - 有人可以解释以下语法及其功能吗?

java - 从文件中取出数字并对它们进行排序