In C++, string concatenation refers to combining two or more strings to create a single, unified text value. This can be done using the +
operator or the append()
method.
Concatenation Using +
Operator
The +
operator allows strings to be combined effortlessly.
Example
Here, the strings bikeBrand
and bikeModel
are joined using +
, resulting in “Ducati Panigale V4”.
#include <iostream> #include <string> using namespace std; int main() { string bikeBrand = "Ducati "; string bikeModel = "Panigale V4"; string fullName = bikeBrand + bikeModel; // Combines the strings cout << "Motorcycle: " << fullName; return 0; }
Adding Spaces During Concatenation
To ensure clarity, spaces can be included manually in the concatenation.
Example
This method creates a space between carBrand
and carModel
, forming “BMW M3”.
#include <iostream> #include <string> using namespace std; int main() { string carBrand = "BMW"; string carModel = "M3"; string fullName = carBrand + " " + carModel; // Adds a space between the strings cout << "Car: " << fullName; return 0; }
Concatenation Using append()
C++ strings are objects, and they come with built-in functions such as append()
for concatenation.
Example
Here, append()
merges jacketBrand
and jacketType
, resulting in “Dainese Leather Racing”.
#include <iostream> #include <string> using namespace std; int main() { string jacketBrand = "Dainese "; string jacketType = "Leather Racing"; string fullDescription = jacketBrand.append(jacketType); // Combines the strings cout << "Jacket: " << fullDescription; return 0; }