Replace string with another string in C++

If you want to replace the entire content of a string with another string in C++, you can simply assign the new string to the existing string. Here’s step by step guide  how you can do this:

Replace strings
1. Include Necessary Headers:

          #include <iostream>
#include <string>

  • #include <iostream> is for standard input and output.
  • #include <string> is for the std::string class.

2.Replace Function:

       void replaceSubstring(string &str, const string &from, const string &to)

       {
       size_t start_pos = 0;
      while ((start_pos = str.find(from, start_pos)) != string::npos)

       {
      str.replace(start_pos, from.length(), to);
      start_pos += to.length(); // Move past the replacement
      }
      }

  • replaceSubstring takes a reference to a string str, a substring to replace from, and the replacement string to.
  • The while loop searches for the substring from in str starting from position start_pos.
  • When from is found, str.replace replaces it with to, and start_pos is updated to continue searching past the newly inserted to.

complete code :

#include <iostream>
#include <string>

using namespace std;

void replaceWholeString(string &str, const string &new_str) {
str = new_str;
}

int main() {
string str = “Hello, world!”;
string new_str = “Goodbye, world!”;

replaceWholeString(str, new_str);

cout << “Modified string: ” << str << endl;

return 0;
}

 

output :

 

Modified string: Goodbye, world!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top