C++ String Concatenation
In this page:
Concatenating with +
The + operator, overloaded for std::string, joins two strings together into a new combined string, working just as naturally as adding two numbers.
Example: Concatenating with +
#include <iostream>
#include <string>
int main() {
std::string first = "Hello, ";
std::string second = "world!";
std::string result = first + second;
std::cout << result << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Concatenating with +=
The += operator appends one string onto the end of another in place, modifying the original string variable rather than creating a brand new one.
Example: Concatenating with +=
#include <iostream>
#include <string>
int main() {
std::string message = "Hello";
message += ", world!";
std::cout << message << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Concatenating Multiple Strings
Several strings and literals can be chained together with + in a single expression, and C++ evaluates the concatenation left to right, building up the final combined string.
Example: Concatenating Multiple Strings
#include <iostream>
#include <string>
int main() {
std::string result = "A" + std::string("B") + "C" + "D";
std::cout << result << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Appending Characters
A single char can be appended to a std::string with += just like another string, letting characters be built up one at a time inside a loop.
Example: Appending Characters
#include <iostream>
#include <string>
int main() {
std::string word = "";
word += 'H';
word += 'i';
std::cout << word << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Mixing Strings and Non-String Values
The + operator cannot directly concatenate a std::string with a raw number; the number must first be converted to a string, commonly with std::to_string, before it can be joined in.
Example: Mixing Strings and Non-String Values
#include <iostream>
#include <string>
int main() {
int age = 25;
std::string message = "Age: " + std::to_string(age);
std::cout << message << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- C++ Arrays Introduction
- C++ Looping Through Arrays
- C++ Omitting Array Size
- C++ Array Size
- C++ Multi-dimensional Arrays
- C++ Arrays & Functions
- C++ Strings (C-style)
- C++ std::string
- C++ String Concatenation
- C++ Converting Strings and Numbers
- C++ String Length
- C++ Accessing String Characters
- C++ using namespace std
- C++ String Methods
- C++ Array of Strings