Home > Back-end >  Replacing User Given Word with Another User Given Word from a std::string
Replacing User Given Word with Another User Given Word from a std::string

Time:12-25

I am trying to replace a given word with another word from a std::string. This is what i tried so far:

int main()
{
    std::string line = "my name is my name and not my name mysometext myto";
    std::string replaceThis,replaceWith;
    
    std::getline(std::cin, replaceThis);
    std::getline(std::cin, replaceWith);
    
    size_t pos = line.find(replaceThis); 
    size_t len = replaceThis.length();
    
    line.replace(pos, len, replaceWith);
    
    std::cout << line << std::endl;
    return 0;
}

Actual Output

my
your
your name is my name and not my name mysometext myto

As you can see only the first occurrence of my is replace with your. I guess i can iterate through each word of line and then do the same for each word and replace my with your. But is there a built in way(like using regex) of doing this instead of reinventing the wheel?

Expected Output

my
your
your name is your name and not your name mysometext myto

As shown in the above expected output i want to replace all occurrences of the word my with your except those that are within other words. That is at the end, i want a std::string that have all the my replaced with your except those occurring within other words.

CodePudding user response:

But is there a built in way(like using regex) of doing this instead of reinventing the wheel?

Yes there is a way of doing this with regex as shown below:

int main()
{
    std::string line{"my name is my name and not my name mysometext myto"}; //this is the original line
    std::cout << line << std::endl;
    
    std::string replaceThis,replaceWith;
    
    std::cout<<"Enter the word that you want to replace in the above: ";
    std::getline(std::cin, replaceThis);
    
    std::cout<<"Enter the word that you want to replace it with: ";
    std::getline(std::cin, replaceWith);
    
    std::regex pattern("\\b"   replaceThis   "\\b");
    std::string replacedLine = std::regex_replace(line, pattern, replaceWith);

    std::cout<<replacedLine<<std::endl;
}

The output of the above program is as follows:

my name is my name and not my name mysometext myto
Enter the word that you want to replace in the above: my
Enter the word that you want to replace it with: your
your name is your name and not your name mysometext myto

which can also be seen here

  • Related