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:
Append a Whole StringThe 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.
Syntaxstr1.append(str2);
Parameter
Return value
// 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;
}
Hello World! GeeksforGeeksAppend 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.
Syntaxstr1.append(str2, pos, num);
Parameter
Return value
// 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;
}
Hello World! GeeksAppend a Character Multiple Times
The string::append() method is used to append the multiple characters at the end of the string.
Syntaxstr.append(num, c);
Parameter
Return value
// 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.
Syntaxstr.append(first, last);
Parameter
Return value
// 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;
}
Hello World! forGeeks
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4