What is std::string::append() in C++?
The built-in function append() is defined in the <string> header. This function is used in string concatenation, similar to the + operator.
It appends specified characters at the end of a string, extending its length.
Return value
The function returns *this, i.e., the change is made directly to the string that calls this function.
This is true for all the different ways of using the function.
Syntax
The function has different syntaxes that we can use, as shown below.
1. String
string& append (const string& str);
The first syntax has only one argument:
str: thestringto be added at the end of thestringthat calls this function.
#include <iostream>using namespace std;int main() {string str1 = "Learn C++ ";string str2 = "with Educative!";cout << "String without appending: " << str1 << endl;str1.append(str2);cout << "String after appending: " << str1;return 0;}
Similarly, a C-string can also be used in the
append()function.
2. Substring
string& append (const string& str, size_t subpos, size_t sublen);
This syntax takes three arguments:
-
str: thestringfrom which the characters will be appended to thestringthat calls this function. -
subpos: the starting index of the substring to be appended. -
sublen: the length of the substring to be appended.
#include <iostream>using namespace std;int main() {string str1 = "Hello from ";string str2 = "with Educative!";cout << "String without appending: " << str1 << endl;str1.append(str2, 5, 10);cout << "String after appending: " << str1;return 0;}
Remember that indexing starts from 0 in C++.
3. Fill
string& append (size_t n, char c);
This syntax takes two arguments:
-
n: the number of timescshould be added. -
c: thecharthat needs to be appended at the end of thestring.
#include <iostream>using namespace std;int main() {string str1 = "Hello from Educative";cout << "String without appending: " << str1 << endl;str1.append(4, '!');cout << "String after appending: " << str1;return 0;}
4. Buffer
string& append (const char* s, size_t n);
This syntax takes two arguments:
-
s: the c-string from which the characters will be appended. -
n: the number of characters to be appended.
#include <iostream>using namespace std;int main() {string str1 = "Hello from ";cout << "String without appending: " << str1 << endl;str1.append("Educative!!!", 9);cout << "String after appending: " << str1;return 0;}