Search code examples
c++replacestd

How do I Search/Find and Replace in a standard string?


How do I replace all occurrences of a substring with another string, for std::strings?

std::string s ("One hello, two hellos.");
s = s.replace("hello", "world");  // something like this

Solution

  • Why not implement your own replace?

    void myReplace(std::string& str,
                   const std::string& oldStr,
                   const std::string& newStr)
    {
      std::string::size_type pos = 0u;
      while((pos = str.find(oldStr, pos)) != std::string::npos){
         str.replace(pos, oldStr.length(), newStr);
         pos += newStr.length();
      }
    }