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.