
This is pretty staight foward. If you want to replace Hello with Heo call the function with these parameters ReplaceWord(str, "Hello", "Heo").
Please note that this example is case sensitive so if you use a lowercase h, it will not replace at all, it wont find the word, it has to be a uppercase H.
#include <iostream>
#include <string>
using namespace std;
void ReplaceWord( std::string& source, const char* WordToFind, const char* WordToReplace );
//program entry point
int main (){
cout<<""<<endl;
string str = "Hello, this is a test";
cout<<"Before replace : "<<endl;
cout<<str<<endl;
cout<<""<<endl;
ReplaceWord(str, "Hello", "Heo");
cout<<"After replace : "<<endl;
cout<<str<<endl;
cout<<""<<endl;
return 0;
}
void ReplaceWord( std::string& source, const char* WordToFind, const char* WordToReplace ){
size_t LengthOfWordToReplace = strlen(WordToFind);
size_t replaceLen = strlen(WordToReplace);
size_t positionToSearchAt = 0;
//search for the next word
while ((positionToSearchAt = source.find(WordToFind, positionToSearchAt)) != std::string::npos)
{
//replace the found word with the new word
source.replace( positionToSearchAt, LengthOfWordToReplace, WordToReplace );
// move to next position
positionToSearchAt += replaceLen;
}
}