How to remove a given word from a string in C++

1 Answer

0 votes
#include <iostream>

std::string removeWord(std::string str, std::string word) {
    if (str.find(word) != std::string::npos) {
        size_t pos = -1;
 
        std::string tmp = word + " ";
        while ((pos = str.find(word)) != std::string::npos)
            str.replace(pos, tmp.length(), "");
 
        tmp = " " + word;
        while ((pos = str.find(word)) != std::string::npos)
            str.replace(pos, tmp.length(), "");
    }
 
    return str;
}
 
int main()
{
    std::string str = "C++ is a high-level general purpose programming language";
    std::string word = "purpose";
 
    str = removeWord(str, word);
    
    std::cout << str;
}




/*
run:

C++ is a high-level general programming language

*/

 



answered Nov 19, 2022 by avibootz

Related questions

1 answer 102 views
102 views asked Nov 18, 2022 by avibootz
1 answer 132 views
1 answer 114 views
1 answer 150 views
2 answers 165 views
2 answers 133 views
1 answer 133 views
...