Concatenating Strings

What Is String Concatenation?

String concatenation joins two or more strings end to end into one longer string. Learn the idea, the order rules, and a short C++ example using +.

On this page
  1. String concatenation joins strings end to end
  2. A simple example
  3. Order matters
  4. Spaces and punctuation are not added for you
  5. Joining more than two strings
  6. Concatenation and formatting
  7. Where joins show up
  8. Related tasks

String concatenation joins strings end to end

String concatenation means joining two or more strings end to end, so they become one longer string. The result holds the characters of the first string, followed by the characters of the next one, and so on. The term comes from a Latin verb meaning to link together.

A simple example

#include <iostream>
#include <string>

int main() {
    std::string first = "Hello, ";
    std::string second = "world!";
    std::string result = first + second;

    std::cout << result << '\n';  // Hello, world!
}

The + operator returns a new string. The two original strings are not changed.

Order matters

The order of the pieces decides the result. Joining "ab" and "cd" in one order gives a different string than the other order:

std::string a = "ab";
std::string b = "cd";

std::cout << a + b << '\n';  // abcd
std::cout << b + a << '\n';  // cdab

Spaces and punctuation are not added for you

C++ joins the characters exactly as given. If neither piece has a space, the words run together:

std::string word = std::string("Hello") + "world";      // "Helloworld"
std::string phrase = std::string("Hello ") + "world";  // "Hello world"

Put the space inside one of the pieces, as the second line does.

Joining more than two strings

Use more + operators to join more pieces. Each + joins the result so far with the next piece:

std::string name = "Ada";
std::string greeting = "Hi, " + name + "!";  // "Hi, Ada!"

Concatenation and formatting

Some languages let you place values inside a string directly. C++ does not have that kind of built-in string interpolation. With a compiler that supports C++20, std::format from <format> fills in placeholders in a template instead. It can be easier to read when a message has many parts.

Where joins show up

Programs join strings all the time. They build messages for users, lines for a log, and file paths from a folder name and a file name. A file path needs the correct separator for the operating system, and a plain string join does not add it for you.

To break a string into pieces, the reverse of joining, see c split string by delimiter. For the full set of ways to join text in C++, see how to concatenate strings in c.

The complete guide to concatenating strings

How to Concatenate Strings in C++
Read the guide

Keep exploring

Guides from other topics

All topics →