How to Concatenate String in C++
To concatenate or combine two or more strings in C++, you may use different ways. These include:
- Using ‘+‘ operator
- A predefined library function append()
- By using strcat() function
The following section shows examples for each of the above-mentioned ways.
Using ‘+’ operator to combine strings in C++
An example of combining two strings:
#include <iostream> #include <string> using namespace std; int main () { string str1 = "C++ "; string str2 = "Tutorials"; string str_concat = str1 + str2; cout <<"The concatenated String: " << str_concat <<"\n\n"; return 0; }
Output:
Concatenating three strings by ‘+’ operator example
#include <iostream> #include <string> using namespace std; int main () { string str1 = "C++ "; string str2 = "Concatenation "; string str3 = "Tutorial"; string str_concat = str1 + str2 + str3; cout <<"The concatenated String: " << str_concat <<"\n\n"; return 0; }
Output:
You can see in the first example, we combined two strings and in the second C++ program, we combined three strings by using the ‘+’ operator.
Second way: using append() function example
Following is the syntax of using the append() function to combine strings:
- That means the append function takes a string as a parameter.
- This string is added to the end of another string object.
- The example below shows the append function usage:
#include <iostream> #include <string> using namespace std; int main () { //Creating String objects string str1 = "C++ "; string str2 = "Append Tutorial"; //Using append function to concat two strings string str_append = str1.append(str2); //Displaying concatenated string cout <<"The concatenated String: " << str_append <<"\n\n"; return 0; }
Output:
Third way of concatenation – Using strcat() function
You can also use strcat() to concatenate two strings easily. Following is the syntax:
- It takes two parameters (char arrays)
- The src parameter is appended to the dest
- This function returns the dest. pointer to the destination string.
- Defined in the <cstring> header file
See a C++ program for strcat() usage:
#include <cstring> #include <iostream> using namespace std; int main() { //Creating char arrays to use in strcat() char dest[30] = "This is C++ "; char src[30] = "concatenation tutorial!"; //Using stringcat function to concat strcat(dest, src); //Displaying end result cout <<"The concatenated string: " << dest <<"\n\n"; return 0; }
Output: