C++string class replace() function

The string class in C++ provides the replace() function for replacing substrings in a string. Its function prototype is as follows:

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

Among them, pos indicates the starting position of the substring to be replaced in the original string, len indicates the length of the substring to be replaced, and str indicates the string to be replaced.

The use of the replace() function is very simple, you only need to pass in the position, length and replacement string of the substring to be replaced. Here is an example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    
    
    string str = "hello world";
    str.replace(0, 5, "hi");
    cout << str << endl; // 输出:hi world
    return 0;
}

In the above example, "hello" in the string is replaced with "hi", and the new string "hi world" is obtained.

Guess you like

Origin blog.csdn.net/Dontla/article/details/130473693