This function is included in the "boost/algorithm/string" library. This library contains some brilliant methods which help in accomplishing string manipulations that are lacking in STL library.
This function is used to replace the last instance of the specified pattern in the input string with a new pattern. It first performs a search for the last occurence of the specified pattern to be replaced and then it replaces it with a new one.
input_string : an input string
seacrh_string : the pattern that has to be replaced in the input_string;
format_string : the pattern that replaces the search_string.
replace_last() performs an inplace replacement. There is another variation present replace_last_copy() which instead of doing an inplace replacement, returns a copy of the modified string.
replace_last() performs a case-sensistive search. There is another variation present ireplace_last() which performs a case-insensitive search. Similarly ireplace_last_copy() returns a copy of modified string instead of doing an inplace replacement.
using namespace std;
using namespace boost::algorithm;
string str1 = "Hello and Welcome Hello and Welcome";
replace_last(str1,"Hello ","Hi ");
string str2 = "Apple Banana Mango Banana Apple";
string str3 = replace_last_copy(str1,"and ","Guys ");
As we can observe from the output we are first performing an inplace replacement where we are replacing the last occurence of "Hello " with "Hi" . Next we are performing replacement on the original string while performing the search case-insensitively. In str3, we are storing the string obtained after performing replacement while searching case-sensitively.