java将两个字符串合并,在Java中逐字合并两个字符串?

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

}

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.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值