-
Notifications
You must be signed in to change notification settings - Fork 7
/
MergeStringsAlternately.java
37 lines (27 loc) · 1.16 KB
/
MergeStringsAlternately.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package array_string;
class MergeStringsAlternately {
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();
}
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!");
}
}