I'm writing a function, which takes three parameters:
target
: Target StringoldVal
: Old substringnewVal
: New Substring (To replace the oldVal)
The task of this function is to find all the occurrence of oldVal
in target
string, and replace them with newVal
.
This is the function I've got at the 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 to the above function:
replace_old_with_new("Hello! hi hi!", "hi", "bye");
should return the string -
"Hello! bye bye!"
But, when I run the code, nothing happens. It seems like I'm stuck in an infinite loop. The cursor keeps blinking on terminal. Is something wrong with my function. I think what might be troubling is the replace
call in the if
block. Is that the correct way to use iterator range in the replace
function call? I can do this with erase
and insert
. But I want to use replace
here.