gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:46:58 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com