Alternatively Merge two Strings
Last Updated :
23 Feb, 2023
Given 2 strings, merge them in an alternate way, i.e. the final string’s first character is the first character of the first string, the second character of the final string is the first character of the second string and so on. And if once you reach end of one string while if another string is still remaining then append the remaining of that string to final string
Examples:
Input : string 1 :"geeks"
string 2 :"forgeeks"
Output: "gfeoerkgseeks"
Explanation : The answer contains characters from alternate strings, and once
the first string ends the remaining of the second string is added to the final string
Input :string 1 :"hello"
string 2 :"geeks"
Output : hgeelelkos
The idea is simple, we create a result string. We one by one append characters of both given strings in alternate style.
C++
#include <bits/stdc++.h>
using namespace std;
string merge(string s1, string s2)
{
string result = "" ;
for ( int i = 0; i < s1.length() ||
i < s2.length(); i++)
{
if (i < s1.length())
result += s1[i];
if (i < s2.length())
result += s2[i];
}
return result;
}
int main()
{
string s1 = "geeks" ;
string s2 = "forgeeks" ;
cout << merge(s1, s2);
return 0;
}
|
Java
public class mergeString {
public static String merge(String s1, String s2)
{
StringBuilder result = new StringBuilder();
for ( int i = 0 ; i < s1.length() || i < s2.length(); i++) {
if (i < s1.length())
result.append(s1.charAt(i));
if (i < s2.length())
result.append(s2.charAt(i));
}
return result.toString();
}
public static void main(String[] args)
{
String s1 = "geeks" ;
String s2 = "forgeeks" ;
System.out.println(merge(s1, s2));
}
}
|
Python3
def merge(s1, s2):
result = ""
i = 0
while (i < len (s1)) or (i < len (s2)):
if (i < len (s1)):
result + = s1[i]
if (i < len (s2)):
result + = s2[i]
i + = 1
return result
s1 = "geeks"
s2 = "forgeeks"
print (merge(s1, s2))
|
C#
using System;
class GFG {
static string merge( string s1, string s2)
{
string result = "" ;
for ( int i = 0; i < s1.Length || i < s2.Length; i++)
{
if (i < s1.Length)
result += s1[i];
if (i < s2.Length)
result += s2[i];
}
return result;
}
static void Main() {
string s1 = "geeks" ;
string s2 = "forgeeks" ;
Console.WriteLine(merge(s1, s2));
}
}
|
Javascript
function mergeString(s1, s2) {
let result = "" ;
for (let i = 0; i < s1.length || i < s2.length; i++) {
if (i < s1.length)
result += s1.charAt(i);
if (i < s2.length)
result += s2.charAt(i);
}
return result;
}
let s1 = "geeks" ;
let s2 = "forgeeks" ;
console.log(mergeString(s1, s2));
|
Complexity Analysis:
- Time Complexity: O(max(L1,L2)), Where L1 and L2 are the lengths of string 1 and string 2 respectively.
- Auxiliary Space: O(L1+L2), Where L1 and L2 are the lengths of string 1 and string 2 respectively.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...