In this C++ tutorial, you will learn how to append a string to another using std::string::append() function, with example programs.
C++ String Append
To append a string to another, you can use std::string::append() function or use C++ Addition Operator +
.
Syntax
The syntax of string.append() function to append string str2
to string str1
is
str1.append(str2);
string.append() function can be chained. Therefore, we can append() multiple strings to this string, in a single statement.
str1.append(str2).append(str3);
Examples
1. Append a string to this string
In the following program, we take two strings: str1
and str2
and append str2
to str1
using string.append() function.
main.cpp
#include <iostream> using namespace std; int main() { string str1 = "Hello"; string str2 = " World"; str1.append(str2); cout << str1 << endl; }
Output
Hello World Program ended with exit code: 0
2. Append multiple strings to this string
In the following program, we take three strings: str1
, str2
and str3
and append str2
and str3
respectively to str1
using string.append() function in a single statement using chaining mechanism.
main.cpp
#include <iostream> using namespace std; int main() { string str1 = "Hello"; string str2 = " World."; string str3 = " Welcome!"; str1.append(str2).append(str3); cout << str1 << endl; }
Output
Hello World. Welcome! Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned how to append a string to another, with the help of example programs.