How to remove the first occurrence of a word from a string in C++

1 Answer

0 votes
#include <iostream>

int main() {
    std::string s = "c c++ c# java c++ groovy java c++";
    std::string word_to_remove = "c++";

    std::string::size_type i = s.find(word_to_remove);

    if (i != std::string::npos)
        s.erase(i, word_to_remove.length() + 1); // + 1 for space 
    
    std::cout << s;
    
    return 0;
}



/*
run:

c c# java c++ groovy java c++

*/

 



answered Jan 19, 2021 by avibootz
...