Concatenate Two Character Arrays

Concatenate Two Character Arrays” is a basic operation of character array. Here, we are given two Character Array of length ‘n’ and ‘m’. Our task is to concatenate both the Character Array and store the result into resultant Character Array.


Example:

INPUT:
String 1: Helpme
String 2: studybro
OUTPUT:
Resultant String: Helpmestudybro

The steps required to concatenate two strings and store the result into resultant string is as follows:

  1. Create a resultant character array of size same as sum of size of given two character arrays.
  2. Copy the first character array to resultant character array and mark the index.
  3. Copy second character array to resultant character array from the marked index.

C++ Program to concatenate two string and store the result into resultant string is as follows:

#include<bits/stdc++.h>  
using namespace std;  
int main()  
{  
    char str1[len],str2[len];  
    cout<<"Enter the first string:\n";  
    cin>>str1;  
    cout<<"Enter the second string:\n";  
    cin>>str2;  
    int len1 = strlen(str1);  
    int len2 = strlen(str2);  
    int length = len1 + len2 + 1;  
    char result[length];  
    int index = 0;  
    for(int i = 0; i < len1; i++)  
    {  
        result[index] = str1[i];  
        index++;  
    }  
    for(int i = 0; i < len2; i++)  
    {  
        result[index] = str2[i];  
        index++;  
    }  
    result[index] = '\0';  
    cout<<"\nThe Resultant string is: "<<result;  
}  

OUTPUT:
Enter the first string: helpme
Enter the second string: studybro
The Resultant string is: helpmestudybro
Time Complexity:
O(n), where n is the length of resultant string.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *