Home C++ Strings Functions assign() C++ std::string assign() Function Definition In C++, std::string::assign() replaces all characters with new content.
It is like operator= with extra overloads. Include <string>.
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax Pass the new contents.
s.assign("hello");
s.assign(5, '*');
s.assign(other, 1, 3); Call What it does s.assign(str)Replace contents with str. s.assign(n, ch)Replace with n copies of ch. s.assign(cstr)Replace with a C-string.
s = "x" is often enough. Use assign when you need a substring or fill overload.
Library declarations string& assign(const string& str);
string& assign(size_type n, char c);
string& assign(const char* s); Parameters Parameter Description source New contents: string, C-string, fill count, iterators, etc.
Return Value Return Value Description string&Reference to *this.
C++ Examples 1. Assign text 2. Assign fill 3. Assign substring Example 1 — Basic assign() Replace with a new word.
#include <iostream>
#include <string>
int main() {
std::string s = "old";
s.assign("new");
std::cout << s << '\n';
return 0;
} How It Works The string starts as "old". assign("new") replaces every character.Printed text is "new". Example 2 — Assign Repeated Char Fill with five dashes.
#include <iostream>
#include <string>
int main() {
std::string s;
s.assign(5, '-');
std::cout << s << '\n';
return 0;
} How It Works assign(5, '-') builds five dashes.Any previous text is discarded. Size becomes 5. Example 3 — Assign Part of Another Take a slice from another string.
#include <iostream>
#include <string>
int main() {
std::string a = "xx";
std::string b = "CodeToFun";
a.assign(b, 4, 2);
std::cout << a << '\n';
return 0;
} How It Works From b, index 4 length 2 is "To". That slice becomes the full contents of a. Earlier "xx" is gone. Frequently Asked Questions What does assign do? It replaces the entire contents of the string.
How is it different from = ? operator= covers common cases; assign adds fill and substring forms.
Does assign keep capacity? It may reuse capacity when the new size fits; otherwise it reallocates.
Can assign throw? Yes, for bad positions or allocation failure.
What is assign_range? C++23 version that assigns from a range.
Next: assign_range() Keep going through the string functions. Replace contents with all characters from a range (C++23).
assign_range() tutorial → CODETOFUN NEWS
Stay Ahead in Tech Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful
Helpful Share Copy link Suggestion