2015-02-08 66 views
0

我在寻找替换全部算法,它在特定位置后替换所有出现的子字符串。到目前为止,我有replace all copy的方法。除了this one之外,没有分配新字符串,最方便的方法是什么?是否存在方便的方法来提升呢?在特定位置后替换所有出现的搜索字符串

#include <iostream> 
#include <string> 
#include <boost/algorithm/string/replace.hpp> 

int main() { 
    std::string str = "1234 abc1234 marker 1234 1234 123 1 12 134 12341234"; 

    const std::string marker("marker"); 
    size_t pos = str.find(marker); 
    if (pos == std::string::npos) { 
     return 0; 
    } 
    pos += marker.length(); 
    std::string str_out(str, 0, pos); 
    boost::algorithm::replace_all_copy(std::back_inserter(str_out), str.substr(pos, std::string::npos), "12", "XXXX"); 
    std::cout << str << std::endl; 
    std::cout << str_out << std::endl; 
} 

回答

0

如果您想要执行就地查找和替换操作,您必须注意性能影响。为了做这样的操作,您可能必须向后读取可能导致缓存行为不正确的字符串,或者执行大量内存洗牌,这也会对性能造成影响。一般来说,最好做一个副本替换操作,因为你将要操作的任何字符串可能会相对较小,并且大多数内存缓存会很容易地处理事情。

如果您必须具有就地查找和替换算法,请使用以下代码(如果您只是查找插入函数)。我对它进行了基准测试,速度非常快。

std::string& find_replace_in_place(std::string &haystack, const std::string needle, const std::string replacement, size_t start = 0){ 
    size_t ret = 0; 
    size_t position = haystack.find(needle, start); 
    while(position != std::string::npos){ 
     haystack.replace(position, needle.length(), replacement); 
     position = haystack.find(needle, position + replacement.length()); 
    } 
    return haystack; 
} 
相关问题