Re-Arrange String in sequence order

Give an string 'abcd' and an another string 'efghij', print the sequence in alternate order, if any of the string is ended, append the rest of the string to the other string

Input :  abcd , efghij

Output: aebfcgdhij

Code:

public static String reArrangeString(String input1, String input2) {
    int length1 = 0, length2 = 0;
    StringBuilder stringBuilder = new StringBuilder();
    while (length1 < input1.length() && length2 < input2.length()) {
        stringBuilder.append(input1.charAt(length1));
        stringBuilder.append(input2.charAt(length2));
        length1++;
        length2++;
    }

    if (length1 != 0) {
        stringBuilder.append(input1.substring(length1));
    }
    if (length2 != 0) {
        stringBuilder.append(input2.substring(length2));
    }
    return stringBuilder.toString();

}

public static void main(String[] args) {
    System.out.println(reArrangeString("abcd", "efghij")); // aebfcgdhij
    System.out.println(reArrangeString("a", "a")); // aa
    System.out.println(reArrangeString("ab", "a")); // aab
    System.out.println(reArrangeString("a", "ab")); // aab
    System.out.println(reArrangeString("ab", "ab")); // abab
    System.out.println(reArrangeString("abc", "abc")); // aabbcc
    System.out.println(reArrangeString("", "abc")); // abc
}
Scroll to Top