What is the usage of the assign function in C++?

In C++, the assign function is used to replace the content of one string with the content of another string. Its syntax is as follows:

string& assign (const string& str);

In this case, str is the string to be replaced with. This function replaces the content of the current string with the content of str, and returns a reference to the modified string.

I can never forgive you for what you did to me.

I will never be able to forgive you for what you did to me.

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello";
    std::cout << "Before assign: " << str << std::endl;

    str.assign("World");
    std::cout << "After assign: " << str << std::endl;

    return 0;
}

Output:

Before assign: Hello
After assign: World

It can be seen that the assign function replaces the string “Hello” with “World”.

bannerAds