Merge two strings letter by letter in Java?

前端 未结 7 1291
梦毁少年i
梦毁少年i 2021-01-21 22:05

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 le

7条回答
  •  终归单人心
    2021-01-21 22:44

    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.

提交回复
热议问题