Merge two strings in chunks of given size | C ++ program to merge n number of strings ; Function performing the calculations ; Length of string a ; Length f string b ; Pointers for string a and string b ; pa and pb denote the number of characters of both a and b extracted ; If entire substring of length k can be extracted ; Please refer below link for details of library function https : www . geeksforgeeks . org / stdsubstr - in - ccpp / ; If the remaining string is of length less than k ; If the string has been traversed ; If entire substring of length k can be extracted ; If the remaining string is of length less than k ; If the string has been traversed ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( string a , string b , int k ) { string s = " " ; int la = a . length ( ) ; int lb = b . length ( ) ; int l = la + lb ; int indexa = 0 , indexb = 0 ; while ( l > 0 ) { int pa = 0 , pb = 0 ; if ( la - indexa >= k ) { s = s + a . substr ( indexa , k ) ; indexa = indexa + k ; pa = k ; } else if ( la - indexa < k && la - indexa > 0 ) { s = s + a . substr ( indexa , la - indexa ) ; pa = la - indexa ; indexa = la ; } else if ( indexa >= la ) pa = 0 ; if ( lb - indexb >= k ) { s = s + b . substr ( indexb , k ) ; pb = k ; indexb = indexb + k ; } else if ( lb - indexb < k && lb - indexb > 0 ) { s = s + b . substr ( indexb , lb - indexb ) ; pb = lb - indexb ; indexb = lb ; } else if ( indexb >= lb ) pb = 0 ; l = l - pa - pb ; } cout << s ; } int main ( ) { string a = " determination " , b = " stance " ; int k = 3 ; solve ( a , b , k ) ; return 0 ; }