How to replace all occurrences of a character in string?

后端 未结 15 1436
别那么骄傲
别那么骄傲 2020-11-22 05:54

What is the effective way to replace all occurrences of a character with another character in std::string?

15条回答
  •  执笔经年
    2020-11-22 06:27

    here's a solution i rolled, in a maximal DRI spirit. it will search sNeedle in sHaystack and replace it by sReplace, nTimes if non 0, else all the sNeedle occurences. it will not search again in the replaced text.

    std::string str_replace(
        std::string sHaystack, std::string sNeedle, std::string sReplace, 
        size_t nTimes=0)
    {
        size_t found = 0, pos = 0, c = 0;
        size_t len = sNeedle.size();
        size_t replen = sReplace.size();
        std::string input(sHaystack);
    
        do {
            found = input.find(sNeedle, pos);
            if (found == std::string::npos) {
                break;
            }
            input.replace(found, len, sReplace);
            pos = found + replen;
            ++c;
        } while(!nTimes || c < nTimes);
    
        return input;
    }
    

提交回复
热议问题