Methods to concatenate string in C/C++ with Examples

There are various ways to concatenate strings. We will discuss each one by one.

Method 1: Using strcat() function.

The strcat() function is defined in “string.h” header file.

Syntax:

char * strcat(char * init, const char * add)

The init and add string should be of character array(char*). This function concatenates the added string to the end of the init string.



Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    char init[] = "this is init";
    char add[] = " added now";
  
    // concatenating the string.
    strcat(init, add);
  
    cout << init << endl;
  
    return 0;
}

chevron_right


Output:

this is init added now

Method 2: Using append() function.

Syntax:

string& string::append (const string& str)

str: the string to be appended.

Here str is the object of std::string class which is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type. The append function appends the add(variable) string at the end of the init string.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    string init("this is init");
    string add(" added now");
  
    // Appending the string.
    init.append(add);
  
    cout << init << endl;
    return 0;
}

chevron_right


Output:

this is init added now

Method 3: Using ‘+’ Operator

Syntax:

string new_string = string init + string add;

This is the most easiest method for concatenation of two string.The + operator simply adds the two string and returns a concatenated string.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    string init("this is init");
    string add(" added now");
  
    // Appending the string.
    init = init + add;
  
    cout << init << endl;
    return 0;
}

chevron_right


Output:

this is init added now


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.