How to find and replace string?

后端 未结 10 1099
感动是毒
感动是毒 2020-11-27 03:51

If s is a std::string, then is there a function like the following?

s.replace(\"text to replace\", \"new text\");
10条回答
  •  一整个雨季
    2020-11-27 04:11

    void replaceAll(std::string & data, const std::string &toSearch, const std::string &replaceStr)
    {
        // Get the first occurrence
        size_t pos = data.find(toSearch);
        // Repeat till end is reached
        while( pos != std::string::npos)
        {
            // Replace this occurrence of Sub String
            data.replace(pos, toSearch.size(), replaceStr);
            // Get the next occurrence from the current position
            pos =data.find(toSearch, pos + replaceStr.size());
        }
    }
    

    More CPP utilities: https://github.com/Heyshubham/CPP-Utitlities/blob/master/src/MEString.cpp#L60

提交回复
热议问题