How to find and replace string?

后端 未结 10 1116
感动是毒
感动是毒 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:19

    Try a combination of std::string::find and std::string::replace.

    This gets the position:

    std::string s;
    std::string toReplace("text to replace");
    size_t pos = s.find(toReplace);
    

    And this replaces the first occurrence:

    s.replace(pos, toReplace.length(), "new text");
    

    Now you can simply create a function for your convenience:

    std::string replaceFirstOccurrence(
        std::string& s,
        const std::string& toReplace,
        const std::string& replaceWith)
    {
        std::size_t pos = s.find(toReplace);
        if (pos == std::string::npos) return s;
        return s.replace(pos, toReplace.length(), replaceWith);
    }
    

提交回复
热议问题