mixString function in Java (CodingBat Solution)

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.

mixString("abc", "xyz") → "axbycz"
mixString("Hi", "There") → "HTihere"
mixString("xxxx", "There") → "xTxhxexre"

Solution :

package com.nextgen4it.problems;

public class mixStringfunction {
                public String mixString(String a, String b) {
                                String result = "";

                                for (int count = 0; count < Math.max(a.length(), b.length()); count++) {
                                                if (count < a.length())
                                                                result += a.substring(count, count + 1);
                                                if (count < b.length())
                                                                result += b.substring(count, count + 1);
                                }
                                return result;
                }
                public static void main(String[] args) {
                                mixStringfunction m=new mixStringfunction();
                                System.out.println(m.mixString("abc", "xyz"));
                }
}


Ouput :


axbycz


EmoticonEmoticon