how do you use string replace in C++?

The string class in C++ provides a replace function that replaces a specified substring within a string. The syntax for using the replace function is as follows:

string& replace (size_t pos, size_t len, const string& str);

pos represents the starting position, len represents the number of characters to be replaced, and str represents the string to replace with. This function will replace len characters starting from pos in the string with str.

The sample code is as follows:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";
    std::cout << "Before replace: " << str << std::endl;

    // 将字符串中的"world"替换为"everyone"
    str.replace(str.find("world"), 5, "everyone");

    std::cout << "After replace: " << str << std::endl;

    return 0;
}

The output result is:

Before replace: Hello, world!
After replace: Hello, everyone!

In addition, the replace function also has several other overloaded versions, allowing users to choose different parameter forms for replacement operations as needed. For detailed usage instructions, please refer to the documentation of the C++ standard library.

bannerAds