CodeBlanks Logo Icon CodeBlanks

String concatenation

Learn to join text with the + operator and append.

Concatenating with +

To put two std::string values side by side you use the + operator. For example std::string fullName = firstName + " " + lastName; joins the first name, a space and the last name into one string.

You can add a string to a string, or a string to a char* literal (double-quoted text). Two char* literals cannot be added directly; you must first convert one to std::string. The result is always a new std::string.

The append method

To add a piece to an existing string you can use the append method: name.append(" Brown");. This works like the + operator, but it modifies the string in place instead of creating a new one.

append is especially efficient when you add pieces repeatedly in a loop; it does not build a new string each time. To print the result, you can use std::cout << name; as usual.

Practice Combine first and last name

The lines that set firstName to "Alex" and lastName to "Brown" are already in place. Now declare fullName by concatenating firstName + " " + lastName and print it with std::cout.

Starter code

main.cpp
#include <iostream>
#include <string>

int main() {
    std::string firstName = "Alex";
    std::string lastName = "Brown";
    // Build fullName by concatenation here
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

int main() {
    std::string firstName = "Alex";
    std::string lastName = "Brown";
    std::string fullName = firstName + " " + lastName;
    std::cout << fullName << std::endl;
    return 0;
}

Expected output

Alex Brown

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the concatenation operator

Question
std::string fullName = firstName____ " " + lastName;
Answer
std::string fullName = firstName+ " " + lastName;

Explanation: The + operator joins strings.

2 What is the result of std::string s = "A"; s.append("B");?

main.cpp
std::string s = "A";
s.append("B");
  • s = "A"
  • s = "B"
  • s = "A B"
  • s = "AB" Correct answer

Explanation: append adds "B" at the end of "A"; the result is "AB".

3 Match each operator/method to its job

Term Meaning
+ Joins two strings
.append(x) Appends at the end
.size() Returns the length
<< Writes to a stream

All lessons in Beginner