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.
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.
The function has different syntaxes that we can use, as shown below.
string& append (const string& str);
The first syntax has only one argument:
str
: the string
to be added at the end of the string
that 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.
string& append (const string& str, size_t subpos, size_t sublen);
This syntax takes three arguments:
str
: the string
from which the characters will be appended to the string
that 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++.
string& append (size_t n, char c);
This syntax takes two arguments:
n
: the number of times c
should be added.
c
: the char
that needs to be appended at the end of the string
.
#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;}
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;}