Regular expressions solution if you have access to c++11 compiler:
#include <iostream>
#include <string>
#include <regex>
void ReplaceString(std::string &subject, const std::string& search, const std::string& replace)
{
// Regular expression to match words beginning with 'search'
std::regex e ("(\\b("+search+"))([^,. ]*)");
subject = std::regex_replace(subject,e,replace) ;
}
int main ()
{
// String to search within and do replacement
std::string s ("Cakemoney, cak, cake, thecakeisalie, cake.\n");
// String you want to find and replace
std::string find ("cak") ;
// String you want to replace with
std::string replace("notcake") ;
ReplaceString(s, find, replace) ;
std::cout << s << std::endl;
return 0 ;
}
Output:
Cakemoney, notcake, notcake, thecakeisalie, notcake.
More about the regular expression string (\\b("+search+"))([^,. ]*)
. Note that after replacing search
this string will be:
(\\b(cak))([^,. ]*)
- \b(cak) - match words beginning with cak regardless of what comes after
- ([^,. ]*) - matches anything up to a
,
, .
, or
(space).
The above basically just rips off the example provided here. The answer is case sensitive, and will also replace punctuation other than the three listed after ^
, but feel free to learn more about regular expressions to make a more general solution.