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:
#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; } |
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:
#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; } |
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:
#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; } |
this is init added now
Recommended Posts:
- Concatenate suffixes of a String
- What happen if we concatenate two string literals in C++?
- C++ program to concatenate a string given number of times
- Different methods to reverse a string in C/C++
- 5 Different methods to find length of a string in C++
- Taking String input with space in C (3 Different Methods)
- Print all distinct characters of a string in order (3 Methods)
- Count consonants in a string (Iterative and recursive methods)
- How to concatenate two integer arrays without using loop in C ?
- C++ Program to concatenate two strings using Operator Overloading
- Concatenate strings in any order to get Maximum Number of "AB"
- std::string::back() in C++ with Examples
- std::string::front() in C++with Examples
- Commonly used String functions in C/C++ with Examples
- Hiding of all overloaded methods with same name in base class
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.



