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++);
}
在此循环中,您将通过前进在每一步上“取得进展”apos
, bpos
, 或两者。一旦字符串用完字符,其对应的pos
停止前进。当两者都存在时循环结束pos
达到他们的目的。
注意:当您需要在循环中附加到字符串时,请使用StringBuilder.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)