std:🧵:append() in C++ (original) (raw)

Last Updated : 20 Jan, 2025

The **string::append() in C++ is used append the characters or the string at the end of the string. It is the member function of **std::string class .

The string::append() function can be used to do the following append operations:

Table of Content

Append a Whole String

The **string::append() method can be used to append the whole string at the end of the given string. We just need to pass the string to be appended as the parameter to string::append () function.

**Syntax

str1.**append(_str2);

**Parameter

**Return value

**Example

C++ `

// C++ Program to show how to append the string // at the end of the given string #include <bits/stdc++.h> using namespace std;

int main() { string str1("Hello World! "); string str2("GeeksforGeeks");

// Append the str2 in to str1
str1.append(str2);

cout << str1 << endl;

return 0;

}

`

Output

Hello World! GeeksforGeeks

Append a Part of the String

The **string::append() method can also be used to append the substring starting from the particular position till the given number of characters.

**Syntax

str1.**append(_str2, pos, num);

**Parameter

**Return value

**Example

C++ `

// C++ Program for appending the substring at // the end of the string #include <bits/stdc++.h> using namespace std;

int main() { string str1("Hello World! "); string str2("GeeksforGeeks ");

// Appends 5 characters from 0th index of
// str2 to str1
str1.append(str2, 0, 5);

cout << str1;

return 0;

}

`

Append a Character Multiple Times

The **string::append() method is used to append the multiple characters at the end of the string.

**Syntax

str.**append(num__, c_);

**Parameter

**Return value

**Example

C++ `

// C++ Program for appending multiple copies // of the same character. #include <bits/stdc++.h> using namespace std;

int main() { string str("Hello Geeks");

// Appends 5 occurrences of '!'
// to str
str.append(5, '!');
cout << str;

return 0;

}

`

Append Characters from a Given Range

The **string::append() method can also be used to append the characters from the given range at the end of the string.

**Syntax

str.**append(_first, last);

**Parameter

**Return value

**Example

C++ `

// C++ Program for appending the // string in the given range #include <bits/stdc++.h> using namespace std;

int main() { string str1("Hello World! "); string str2("GeeksforGeeks");

// Appends all characters from
// str2.begin()+5, str2.end() to str1
str1.append(str2.begin() + 5, str2.end());

cout << str1;
return 0;

}

`

Output

Hello World! forGeeks