I'm looking for the most efficient (in terms of "fastest") way to replace all occurrences of a substring within a string with another string. All I've came up with so far is:
std::string StringReplaceAll(const std::string &cstSearch, const std::string &cstReplace, const std::string &cstSubject) { if(cstSearch.length() > cstSubject.length() || cstSearch == cstReplace || cstSubject.empty() || cstSearch.empty() || cstSubject.find(cstSearch) == std::string::npos) { return cstSubject; } std::ostringstream ossReturn; std::string::const_iterator ci(cstSubject.cbegin()); const std::string::const_iterator::difference_type ciFindSize(std::distance(cstSearch.cbegin(), cstSearch.cend())); for(std::string::const_iterator ciNow; (ciNow = std::search(ci, cstSubject.cend(), cstSearch.cbegin(), cstSearch.cend())) != cstSubject.cend(); ci = ciNow) { std::copy(ci, ciNow, std::ostreambuf_iterator<char> (ossReturn)); std::copy(cstReplace.cbegin(), cstReplace.cend(), std::ostreambuf_iterator<char> (ossReturn)); std::advance(ciNow, ciFindSize); } std::copy(ci, cstSubject.cend(), std::ostreambuf_iterator<char> (ossReturn)); return ossReturn.str(); } ... and this one is way(!!!) too slow for my needs :-(
Looking forward to learn from you guys!