Programming & Development / April 18, 2025

Merging Two Strings Alternately in Java โ€“ Explained with Example

java string merge merge alternately java string manipulation java alternate character merge java java interview coding string buffer java string algorithm java merge two strings java

Article:

Merging two strings alternately is a common string manipulation problem that often comes up in interviews and coding challenges. In this article, we'll explore a simple yet effective way to solve this using Java.

๐Ÿ“ฆ Package and Class Overview

java

package array_string;

class MergeStringsAlternately {
    ...
}
  • Package: array_string โ€“ Groups string-related classes for organization.
  • Class: MergeStringsAlternately โ€“ Contains the logic to merge two strings alternately.

๐Ÿ” Method: mergeAlternately

java

public String mergeAlternately(String firstString, String secondString) {
    StringBuffer combined = new StringBuffer();
    int index = 0;

    while (index < firstString.length() || index < secondString.length()) {
        if (index < firstString.length()) {
            combined.append(firstString.charAt(index));
        }
        if (index < secondString.length()) {
            combined.append(secondString.charAt(index));
        }
        index++;
    }

    return combined.toString();
}

๐Ÿ’ก Explanation:

  • Parameters:
  • firstString: The first input string.
  • secondString: The second input string.
  • StringBuffer combined: Used to construct the merged string efficiently.
  • Looping logic:
  • The loop runs as long as at least one of the strings has characters left.
  • At each step:
  • If the current index exists in firstString, add that character.
  • Then do the same for secondString.
  • Return Value: The merged string built by alternating characters.

๐Ÿงช Testing in main()

java

public static void main(String[] args) {

    MergeStringsAlternately solution = new MergeStringsAlternately();

    String result1 = solution.mergeAlternately("abc", "pqr");
    assert "apbqcr".equals(result1) : "Test case 1 failed";

    String result2 = solution.mergeAlternately("ab", "pqrs");
    assert "apbqrs".equals(result2) : "Test case 2 failed";

    String result3 = solution.mergeAlternately("abcd", "pq");
    assert "apbqcd".equals(result3) : "Test case 3 failed";

    System.out.println("All test cases passed!");
}

๐Ÿ”Ž Breakdown of Test Cases:

  • Test Case 1:
  • Input: "abc", "pqr"
  • Merged Output: "apbqcr"
  • Test Case 2:
  • Input: "ab", "pqrs"
  • Merged Output: "apbqrs" (remaining "rs" is appended at the end)
  • Test Case 3:
  • Input: "abcd", "pq"
  • Merged Output: "apbqcd" (remaining "cd" is appended at the end)

The use of assert ensures each result matches expectations. If all pass, it prints a success message.

โœ… Summary

This example is a clean and efficient way to merge two strings alternately. It's a great demonstration of:

  • Looping through strings with different lengths
  • Using StringBuffer for mutable string construction
  • Writing meaningful test cases with assertions

This kind of logic is perfect for interviews and can be extended to solve more complex string combination problems.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex