String Concatenation
Combining Strings
Concatenation means joining strings together. In C++, you can concatenate strings using the +
operator.
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;
return 0;
}
Output
John Doe
Appending Strings
You can also append to strings using the +=
operator or the append()
method.
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
str += " World"; // Using +=
str.push_back('!'); // Append a single character
// str.append("!"); // Equivalent way to append a C-string
cout << str;
return 0;
}
Output
Hello World!
Concatenation Rules
- You can concatenate std::string
objects with other std::string
objects.
- You can concatenate std::string
objects with C-style strings (string literals or const char*
).
- You can concatenate std::string
objects with single characters (e.g., '!'
).
- You cannot use +
between two **string literals** (both operands are const char*
), but adjacent string literals without +
are concatenated at compile time.
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "Hello";
string s2 = s1 + " World"; // OK: string + C-string
string s3 = "Hello " + s1; // OK: C-string + string
// string bad = "Hello" + " World"; // Error: const char* + const char*
// Adjacent string literals (no '+') are concatenated at compile time:
const char* lit = "Hello" " World"; // OK -> "Hello World"
using namespace std::string_literals; // C++14 UDL: "..."s -> std::string
string s4 = "Hello"s + " World"s; // OK: string + string via "s" literal
cout << s2 << "\n" << s3 << "\n" << lit << "\n" << s4;
return 0;
}
Output
Hello World Hello Hello Hello World Hello World
ℹ️ Note: Order usually does not matter: both <code>string + const char*</code> and <code>const char* + string</code> are supported. To use <code>+</code> between two literals, wrap at least one side as <code>std::string</code> (e.g., <code>string("Hello") + " World"</code>) or use the C++14 <code>"s"</code> literal.
Efficiency Tips
Each operator+
creates a new string. Prefer +=
/append()
in loops and consider reserving capacity to reduce reallocations.
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string first = "John";
string last = "Doe";
string builder;
builder.reserve(first.size() + 1 + last.size());
builder += first;
builder += ' ';
builder += last;
cout << builder; // "John Doe"
return 0;
}
Output
John Doe
ℹ️ Note: For many parts, <code>std::ostringstream</code> or <code>std::format</code> (C++20) can also be convenient for building strings.