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
Please Login to comment...