How to remove all substrings from a string

前端 未结 4 941
终归单人心
终归单人心 2020-12-01 23:56

How to remove all instances of the pattern from a string?

string str = \"red tuna, blue tuna, black tuna, one tuna\";
string pattern = \"tuna\";
4条回答
  •  旧巷少年郎
    2020-12-02 00:47

    Try something like:

    void replaceAll(std::string& str, const std::string& from, const std::string& to) {
        if(from.empty())
            return;
        size_t start_pos = 0;
        while((start_pos = str.find(from, start_pos)) != std::string::npos) {
            str.replace(start_pos, from.length(), to);
            start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
        }
    }
    

    From Replace part of a string with another string

提交回复
热议问题