Concatenate multiple strings in C++
This post will discuss how to concatenate multiple strings in C++.
1. Using + operator
The most common approach to concatenate multiple strings in C++ is to use the + operator, which is overloaded for string objects.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> int main() { std::string s1("Hello"); std::string s2(" "); std::string s3("World"); std::string s = s1 + s2 + s3; std::cout << s; return 0; } |
Output:
Hello World
2. Using std::stringstream function
Another plausible way to concatenate multiple strings in C++ is to use string streams. The idea is to insert all individual strings into std::stringstream and then dump the buffer contents into a string using its str() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <string> #include <sstream> int main() { std::string s1("Hello"); std::string s2(" "); std::string s3("World"); std::stringstream ss; ss << s1 << s2 << s3; std::string s = ss.str(); std::cout << s; return 0; } |
Output:
Hello World
3. Using std::string::append function
Finally, we can also use the string’s append() function that appends the specified string at the end of the string object.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> #include <sstream> int main() { std::string s1("Hello"); std::string s2(" "); std::string s3("World"); std::string s; s.append(s1); s.append(s2); s.append(s3); std::cout << s; return 0; } |
Output:
Hello World
That’s all about concatenating multiple strings in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)