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 thestd::stringclass.
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
}
}
replaceSubstringtakes a reference to a stringstr, a substring to replacefrom, and the replacement stringto.- The
whileloop searches for the substringfrominstrstarting from positionstart_pos. - When
fromis found,str.replacereplaces it withto, andstart_posis updated to continue searching past the newly insertedto.
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!