i'm writing function, takes 3 parameters:
target
: target stringoldval
: old substringnewval
: new substring (to replace oldval)
the task of function find occurrence of oldval
in target
string, , replace them newval
.
this function i've got @ moment:
std::string replace_old_with_new(std::string target, std::string oldval, std::string newval) { std::cout << "target : " << target << ", oldval: " << oldval << ", newval: " << newval << "\n"; std::string::iterator begin = target.begin(); std::string::iterator oldvalbegin = oldval.begin(); while (begin != target.end()) { if (*begin == *oldvalbegin) { target = target.replace(begin, begin + oldval.size(), oldval); begin = target.begin(); } else { ++begin; } } return target; }
the following call above function:
replace_old_with_new("hello! hi hi!", "hi", "bye");
should return string -
"hello! bye bye!"
but, when run code, nothing happens. seems i'm stuck in infinite loop. cursor keeps blinking on terminal. wrong function. think might troubling replace
call in if
block. correct way use iterator range in replace
function call? can erase
, insert
. want use replace
here.
strings smarter give them credit for. know how search, don't have yourself.
int pos = 0; int match_pos; std::string result; while ((match_pos = target.find(oldval, pos)) != std::string::npos) { result += target.substr(pos, match_pos - pos); result += newval; pos = match_pos + target.size(); } result += target.substr(pos, std::string::npos);
sorry, sketch; not tested, idea.
Comments
Post a Comment