Merge two strings letter by letter in Java?

前端 未结 7 1292
梦毁少年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:57

    Another approach using StringBuilder and char[]. Works as long as the first is longer than the second, which is guaranteed by the first method.

    public String mixString(String a, String b) {
        if (b.length() > a.length())
            return mixString(new StringBuilder(b), a.toCharArray(), 0);
        return mixString(new StringBuilder(a), b.toCharArray(), 1);
    }
    
    public String mixString(StringBuilder ab, char[] b, int start) {
        int i = 0;
        for (char c : b)
            ab.insert(i++*2 + start, "" + c);
        return ab.toString();
    }
    

提交回复
热议问题