Merge two strings letter by letter in Java?
java, string
Solution
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`.
Problem
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; } ```