how to replace part of string with new string c++

To replace part of a string with a new string in C++, you can use the replace function from the std::string class. Here are the steps to do it:

  1. Include the necessary header file:
#include <string>
  1. Declare a string variable and initialize it with the original string:
std::string str = "The quick brown fox jumps over the lazy dog";
  1. Use the replace function to replace the desired part of the string. The function takes three parameters: the starting index of the substring to be replaced, the length of the substring to be replaced, and the new string that will replace it. In this example, let's replace the word "brown" with "red":
str.replace(str.find("brown"), 5, "red");
  1. Print the modified string to verify the replacement:
std::cout << str << std::endl;

The complete code looks like this:

#include <iostream>
#include <string>

int main() {
    std::string str = "The quick brown fox jumps over the lazy dog";
    str.replace(str.find("brown"), 5, "red");
    std::cout << str << std::endl;
    return 0;
}

When you run this code, it will output:

The quick red fox jumps over the lazy dog

Let me know if you need further assistance!