Problems with std::string.replace()
Mar 16, 2019 at 12:16pm UTC
I'm trying to write a function, which replaces all occurrences of a
std::string
with a different one. Naturally, I tried using
std::string.replace()
as a first bet but that doesn't seem to be working.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <string>
void Func( std::string &s, const std::string &oldVal, const std::string &newVal ) {
auto curr = s.cbegin();
while ( curr <= ( s.cend() - oldVal.size() ) ) {
if ( std::string( curr, curr + oldVal.size() ) == oldVal ) {
s.replace( curr, curr + oldVal.size(), newVal );
curr += newVal.size();
} else {
++curr;
}
}
}
int main() {
std::string success = "i went thru a river, thru a deep forest" ;
Func( success, "thru" , "through" );
std::string error = "i went thru a river, thru it was quite deep" ;
Func( error, "thru" , "through" );
return 0;
}
What is causing the second
std::string
to output:
cannot seek string iterator because the iterator was invalidated (e.g. reallocation occured, or the string was destroyed)
? Should I rather use
std::string.insert()
and
std::string.erase()
to properly update the iterator
curr
?
Last edited on Mar 24, 2019 at 3:57pm UTC
Mar 16, 2019 at 1:08pm UTC
Try...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
#include <string>
void Func (std::string& str, const std::string& oldStr, const std::string& newStr) {
std::string::size_type pos = 0u;
while ((pos = str.find (oldStr, pos)) != std::string::npos) {
str.replace (pos, oldStr.length (), newStr);
pos += newStr.length ();
}
}
int main () {
std::string success = "i went thru a river, thru a deep forest" ;
Func (success, "thru" , "through" );
std::cout << success << "\n\n" ;
std::string error = "i went thru a river, thru it was quite deep" ;
Func (error, "thru" , "through" );
std::cout << error << "\n\n" ;
return 0;
}
Topic archived. No new replies allowed.