-
String replace
Hey everyone,
I'm trying to find a string within a larger string, then replace it with a value. Here is an example (sudocode)?
Code:
string 1 = "this is REPLACE_STRING_HERE!";
string 2 = "really cool"
string1.replace("REPLACE_STRING_HERE", string2);
cout << string1 << endl; //outputs this is really cool!
How would I go about doing this?
Thanks,
Matt N
-
Use find to find the location of the search string, then use that location plus the search string's size to get the range to replace with the new string.
-
You're quite close already. But replace() wants a position and a length or a pair of iterators to specify the position, so you need to use string::find() to get them.
Code:
pos = s.find(search_string);
if(pos != string::npos) {
s.replace(pos, search_string.length(), replacement);
}