C++ 替换特定位置后出现的所有搜索字符串
我正在寻找替换所有算法,该算法替换了特定位置后出现的所有子字符串。到目前为止,我已经采取了C++ 替换特定位置后出现的所有搜索字符串,c++,boost,replaceall,C++,Boost,Replaceall,我正在寻找替换所有算法,该算法替换了特定位置后出现的所有子字符串。到目前为止,我已经采取了替换所有副本的方法。在不分配新字符串的情况下,最方便的方法是什么?是否存在使用boost执行此操作的便捷方法 #include <iostream> #include <string> #include <boost/algorithm/string/replace.hpp> int main() { std::string str = "1234 abc123
替换所有副本的方法。在不分配新字符串的情况下,最方便的方法是什么?是否存在使用boost执行此操作的便捷方法
#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;
}
#包括
#包括
#包括
int main(){
std::string str=“1234 abc1234标记1234 1234 1231 12 134 12341234”;
常量std::字符串标记(“标记”);
大小\u t pos=str.find(标记);
if(pos==std::string::npos){
返回0;
}
pos+=marker.length();
std::字符串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如果您想执行就地查找和替换操作,您必须了解性能影响。为了执行此类操作,您可能必须向后读取字符串,这可能会导致糟糕的缓存行为,或者执行大量内存洗牌,这也可能会对性能造成不利影响。一般来说,最好这样做复制中的替换操作,因为您将要操作的任何字符串都可能相对较小,并且大多数内存缓存将很容易处理事情
如果您必须有一个就地查找和替换算法,如果您只是在寻找一个插入函数,请使用下面的代码。我对它进行了基准测试,速度非常快
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;
}