+92 332 4229 857 99ProjectIdeas@Gmail.com

How to concatenate two strings (C++ tutorial)


Concatenate two strings
Concat() function takes 2 strings as its input parameter and returns a concatenated string.
For example
If first string is “Saad” and the second string is “Qureshi”, then it will return a string “SaadQureshi
Code of Concat()
char * Concat( char * str1 , char * str2 )
{
      char * str3;
      str3 = new char [ strlen( str1 ) + strlen( str2 ) ];
      int i = 0;

      for( int j = 0; j < strlen( str1 ); j++ )
            str3[i++] = str1[j];

      for( int k = 0; k < strlen( str2 ); k++ )
            str3[i++] = str2[k];

      str3[i] = '\0';

      return str3;
}
Summary of Concat()
First of all a new string str3 is created and its length is the sum of both the input strings str1 and str2.
An index variable i is declared and initialized to 0 – which is used to address the index of the newwly created string str3.
First for loop copies the first string str1 to str3.
Second for loop copies the second string str2 to str3.
NULL character is assigned at the last index of the string str3, which identifies that the string has ended.
At the end string str3 is returned - which is the result of concatenation of str1 and str2.

Code
#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

char * Concat( char * str1 , char * str2 )
{
      char * str3;
      str3 = new char [ strlen( str1 ) + strlen( str2 ) ];
      int i = 0;

      for( int j = 0; j < strlen( str1 ); j++ )
            str3[i++] = str1[j];

      for( int k = 0; k < strlen( str2 ); k++ )
            str3[i++] = str2[k];

      str3[i] = '\0';

      return str3;
}

int main()
{
      char str1[] = "Saad";
      char str2[] = "Qureshi";
     
      cout << "String 1            : " << str1 << endl;
      cout << "String 2            : " << str2 << endl;
      cout << "Concatenated string : " << Concat( str1 , str2 );

      _getche();
      return 0;
}

Output
String 1            : Saad
String 2            : Qureshi
Concatenated string : SaadQureshi

0 comments: