替换特定位置后出现的所有搜索字符串
Replace all occurrences of the search string after specific position
我正在寻找替换所有算法,该算法替换了特定位置后出现的所有子字符串。到目前为止,我有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;
}
相关文章:
- 在对象数组中搜索字符串并返回相应值的函数
- 在 QTextEdit 中搜索字符串
- C++ 中用于搜索字符串模式的正则表达式
- 如何在文件中搜索字符串并打印包含该字符串的行
- 搜索字符串是否至少包含一次从 0 到 9 的所有数字的最有效方法
- 从文件中提取的数据中的C 搜索字符串失败
- 在数组中搜索字符串的所有术
- 在 main 中搜索字符串的结尾时出现分段错误,但不在函数C++中搜索
- 在字符串中搜索字符串序列
- c++搜索字符串列表中的特定字符串
- 从文件中读取一行,并在其中搜索字符串(c++)
- 在向量中搜索C++字符串s中的单词
- 在另一个进程的内存中搜索字符串的每个匹配项
- 当搜索字符串有空格时查找字符串
- 在结构向量中搜索字符串C++
- 搜索字符串中的第一个字符不同于"X"
- 搜索字符串(只查找完全匹配的字符串,不忽略大写或小写字符
- 如何在C++中搜索字符串数组
- 替换特定位置后出现的所有搜索字符串
- 搜索字符串以使用递归查找另一个字符串