How to join strings in C++

Let’s have a look at how to join strings in C++ language.

It is very much needed to join strings when there are multiple words or sentences which must be in a single word or sentence.

There are various ways in C++ for joining a string.

First Method

In this method, we can just concatenate two strings using the ‘+’ symbol to form a new one.

#include <iostream>
#include <string>
using namespace std;
 
int main () {
  string fname = "code";
  string lname = "speedy";
  string fullName = fname + lname;
  cout << fullName;
  return 0;
}

Output:

codespeedy

we can see that the output string formed is the combination of two separate strings.

Second method

In C++, as the string is an object, we can perform append function two concatenate two strings.

#include <iostream>
#include <string>
using namespace std;
 
int main () {
 string fname = "code";
 string lname = "speedy";
 string fullName = fname.append(lname);
 cout << fullName;

  return 0;
}

Output

codespeedy

We see that the output obtained is a combination of two strings.

Third method

In this method, we use cstring header to use strcat function.

we have to declare strings with the character array.

#include <iostream>
#include <cstring>
using namespace std;

int main()
{ 
    char fname[30] = "code"; 
    char lname[30] = "speedy";
    strcat(fname, lname); 
    cout << fname;

    return 0;
}

Output

codespeedy

In this tutorial, We learnt the various methods of joining strings in C++.

Leave a Reply

Your email address will not be published.