3 Ways To Concatenate Strings in C++

This tutorial is a guide to concatenating two strings in C++ by 3 methods. There are in total many ways to do this task but today we will discuss the most useful ones.

You can check: How to join strings in C++

Method 1: strcat() method

The very first way is to use strcat() which is an in-built function in C++ whose function is to concatenate a string in C++ and its syntax is-

strcat(String1,String2)

For this, we will create two character arrays or call them strings and then use strcat() with these two character arrays/strings as parameters as-

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char arr1[]="Code";
    char arr2[]="Speedy";
    strcat(arr1,arr2);
    cout<<arr1;
    
}

Here the string or char arr1 is concatenated with arr2 and the result is appended in the arr1.

Output:CodeSpeedy

Method2: append() method

The second method is based on the append() method. The syntax of append() in C++ is

String1.append(String2);

The coding part would be-

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    string str1("Code");
    string str2("Speedy");
    str1.append(str2);
    cout<<str1;
    
}

The append function does not return any value, it just extends the string by the given value.

Output-CodeSpeedy

Method 3: + operator

Method 3 is indeed very simple just by using a single operator between the two strings and it will concatenate and do our task so easily and efficiently. So the operator that will work in between two strings is ‘+’.

The syntax for this operator is-

String1+String2

As we all know about this operator, there is no need for any kind of explanation for this operator. We just need to use this operator between two strings and print the result on the output screen as-

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    string str1("Code");
    string str2("Speedy");
    str1=str1+str2;
    cout<<str1;
    
}
Output: CodeSpeedy

We have completed the task to concatenate two strings by three methods. I hope you enjoyed reading this tutorial. Stay connected for more such informative articles.

Leave a Reply

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