How to Merge Two Strings Alternatively

In this example, we’ll see how to merge two strings alternatively:

Input:
String a = "aaa";
String b = "bbb";

Output:
ababab

1. Java

public class MergeTwoStringsAlternatively {
    public static void main(String[] args) {
            mergeStrings("hello", "world");
    }

    private static void mergeStrings(String one, String two) {
        String result = "";
        for (int i = 0; i < one.length() | i < two.length(); i++) {
            if (i < one.length())
                result += one.charAt(i);
            if (i < two.length())
                result += two.charAt(i);
        }
        System.out.println(result);
    }
}

Output:

hweolrllod

Complete Java Solutions can be found here: Github Link

The complete list can be found here: Practise Programming Questions

Leave a Comment