#include <boost/algorithm/string/replace.hpp>
// To replace the source string
std::string in_place = "blah#blah";
boost::replace_all(in_place, "#", "@");
// If you store the source string in another string without replacing it
const std::string input = "blah#blah";
std::string output = boost::replace_all_copy(input, "#", "@");
std::string ReplaceAll(std::string &str, const std::string& from, const std::string& to){
size_t start_pos = 0; //string check from the beginning
while((start_pos = str.find(from, start_pos))!= std::string::npos) //from
{
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // avoid duplicate checks and from.For length() > to.length()
}
return str;
}
...
std::cout << ReplaceAll(string("Number Of Beans"), std::string(" "), std::string("_")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("X")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("h")) << std::endl;
Results)
Number_Of_Beans
XXjXugtXty
hhjhugthty
#include <algorithm>
#include <string>
int main() {
std::string s = "example string";
char from = 'e';
char to = '!';
std::replace( s.begin(), s.end(), from, to); // replace all 'x' to 'y'
std::cout << s << endl;
}
Results)
!xampl! string
© 2024 OneMinuteCode. All rights reserved.