Replace part of a string with another string

前端 未结 15 2575
终归单人心
终归单人心 2020-11-22 02:54

Is it possible in C++ to replace part of a string with another string?

Basically, I would like to do this:

QString string(\"hello $name\");
string.re         


        
15条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 03:27

    If all strings are std::string, you'll find strange problems with the cutoff of characters if using sizeof() because it's meant for C strings, not C++ strings. The fix is to use the .size() class method of std::string.

    sHaystack.replace(sHaystack.find(sNeedle), sNeedle.size(), sReplace);
    

    That replaces sHaystack inline -- no need to do an = assignment back on that.

    Example usage:

    std::string sHaystack = "This is %XXX% test.";
    std::string sNeedle = "%XXX%";
    std::string sReplace = "my special";
    sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
    std::cout << sHaystack << std::endl;
    

提交回复
热议问题