Alternatively Merge two Strings in Java | C ++ code to alternatively merge two strings ; Function for alternatively merging two strings ; To store the final string ; For every index in the strings ; First choose the ith character of the first string if it exists ; Then choose the ith character of the second string if it exists ; Driver code
#include <bits/stdc++.h> NEW_LINE 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 ; }