Replacing a specific word in a string

Asked 2 years ago, Updated 2 years ago, 97 views

string msg1 = "hello, hello, kk, kkkk, rrrr";

I want to change hello to bye when I'm with string.replace() is not the function I want

c++ stdstring

2022-09-22 08:24

1 Answers

#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


2022-09-22 08:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.