How to String concatenation in C++ ?


String concatenation in C++ can be done using the + operator or the += operator.

Here are examples of both methods:

Using the + operator:

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello";
    std::string str2 = "World";
    std::string result = str1 + " " + str2;
    std::cout << result << std::endl;
    return 0;
}

Output:

Hello World

Using the += operator:

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello";
    std::string str2 = "World";
    str1 += " ";
    str1 += str2;
    std::cout << str1 << std::endl;
    return 0;
}

Output:

Hello World


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.