替换特定位置后出现的所有搜索字符串

Replace all occurrences of the search string after specific position

本文关键字:搜索 字符串 定位 位置 替换      更新时间:2023-10-16

我正在寻找替换所有算法,该算法替换了特定位置后出现的所有子字符串。到目前为止,我有replace all copy方法。除此之外,在不分配新字符串的情况下,最方便的方法是什么?有没有方便的方法来做助推?

#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;
}

如果要执行就地查找和替换操作,则必须注意性能影响。为了执行这样的操作,您可能需要向后读取字符串,这可能会导致不良的缓存行为,或者进行大量的内存洗牌,这也可能对性能不利。一般来说,最好在复制操作中进行替换,因为您要操作的任何字符串都可能相对较小,而且大多数内存缓存都可以很容易地处理。

如果您必须有一个就地查找和替换算法,如果您只是在寻找一个插入函数,请使用以下代码。我做了基准测试,速度很快。

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;
}