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:

  1. 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.

2. Substring


string& append (const string& str, size_t subpos, size_t sublen);

This syntax takes three arguments:

  1. str: the string from which the characters will be appended to the string that calls this function.

  2. subpos: the starting index of the substring to be appended.

  3. 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:

  1. n: the number of times c should be added.

  2. 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;
}

4. Buffer


string& append (const char* s, size_t n);

This syntax takes two arguments:

  1. s: the c-string from which the characters will be appended.

  2. 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;
}

Free Resources