Concatenating strings

C++:
Concatenating strings

How to:

In C++, we’ve got a few ways to concatenate strings. Here’s a taste using std::string and the plus (+) operator:

#include <iostream>
#include <string>

int main() {
    std::string hello = "Hello, ";
    std::string world = "World!";
    
    std::string greeting = hello + world;
    
    std::cout << greeting << std::endl; // Outputs: Hello, World!
    return 0;
}

Quick and simple, yeah? But, we can also use append():

#include <iostream>
#include <string>

int main() {
    std::string hello = "Hello, ";
    hello.append("World!");
    
    std::cout << hello << std::endl; // Outputs: Hello, World!
    return 0;
}

Or even operator+= if you feel like it:

#include <iostream>
#include <string>

int main() {
    std::string hello = "Hello, ";
    hello += "World!";
    
    std::cout << hello << std::endl; // Outputs: Hello, World!
    return 0;
}

Deep Dive

Historically, C++ took over from C, which used character arrays and functions like strcat() for string work. It was messier and more error-prone.

Modern C++ improved the scene with std::string. It’s safer, easier to read, and gives you options. If std::string isn’t your jam, there’s std::stringstream or even std::format (from C++20) for the formatting fans.

Under the hood, concatenating strings involves memory allocation and copying. Done carelessly, it can hit your program’s performance like a brick. Smart pointers and move semantics alleviate some pain here.

Let’s not forget about the alternatives - libraries like Boost, or handling UTF-8 with std::string_view for zero-copy operations on modern C++.

See Also