Lesson 48 +10 XP

String Concatenation

String Concatenation

Joining strings together is called concatenation. In C++, the + operator does the joining.

The + operator

string firstName = "Ada ";
string lastName = "Lovelace";
string fullName = firstName + lastName;

Result: Ada Lovelace

Watch the spaces

Strings join exactly as they are - nothing is inserted between them. "Ada" plus "Lovelace" gives "AdaLovelace". The space in the example above came from the trailing space inside "Ada ".

Concatenate while printing

cout << "Hello " << "world!" << endl;   // Hello world!

You can also glue pieces together with << on the way out. Both styles work.

Shortcut: +=

string msg = "Hi";
msg += " there";   // msg is now "Hi there"

+= appends text to the end of an existing string.

TL;DR

  • + joins two strings into a new one.
  • No automatic spaces: include them yourself.
  • cout << "a" << "b" prints "ab".
  • string += "more" appends to the existing string.