Replace the part of a string with another string ?

Replace the part of a string with another string ?

Asked on October 26, 2018 in String.
Add Comment


  • 3 Answer(s)

    Use this code

    bool replace(std::string& str, const std::string& from, const std::string& to)
    {
      size_t start_pos = str.find(from);
      if(start_pos == std::string::npos)
        return false;
      str.replace(start_pos, from.length(), to);
      return true;
    }
    std::string string("hello $name");
    replace(string, "$name", "Somename");
    
    Answered on October 26, 2018.
    Add Comment

    The user use the std::regex with the help of the C++11 :

    std::string string("hello $name");
    
    string = std::regex_replace(string, std::regex("\\$name"), "Somename");
    
    
    Answered on October 26, 2018.
    Add Comment

    This  code is used to Replace the part of a string with another string:

    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'
      }
    }
    
    Answered on October 26, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.