C++ - Strings: Concatenation
Overview
Estimated time: 15–25 minutes
Combine strings using +, +=, and append. Learn how to safely mix string literals and std::string values.
Learning Objectives
- Concatenate std::string values and literals.
- Know when to convert C-strings explicitly.
Prerequisites
Examples
#include <string>
#include <iostream>
int main(){
std::string a = "Hello";
std::string b = a + ", " + "world"; // literal + string is fine if one side is std::string
std::string c = a; c += "!";
std::string d; d.append("Hi");
std::cout << b << "\n" << c << "\n" << d << "\n";
}
Common Pitfalls
- "a" + "b" does not concatenate C string literals (it performs pointer arithmetic); ensure a std::string is involved:
std::string("a") + "b"
.