只是为了好玩,我正在尝试编写一个类似于文字处理器的查找和替换程序。我想知道是否有人可以帮助我找出我做错了什么(我遇到了 Timeout
错误)并且可以帮助我编写一个更优雅的过程。
#include <iostream>
#include <string>
void find_and_replace(std::string& text, const std::string& fword, const std::string& rword)
{
for (std::string::iterator it(text.begin()), offend(text.end()); it != offend;)
{
if (*it != ' ')
{
std::string::iterator wordstart(it);
std::string thisword;
while (*(it+1) != ' ' && (it+1) != offend)
thisword.push_back(*++it);
if (thisword == fword)
text.replace(wordstart, it, rword);
}
else {
++it;
}
}
}
int main()
{
std::string S("Yo, dawg, I heard you like ...");
std::string f("dawg");
std::string w("dog");
// Replace every instance of the word "dawg" with "dog":
find_and_replace(S, f, w);
std::cout << S;
return 0;
}
最佳答案
像大多数编辑器一样的查找和替换会涉及常规
表达式。如果你要找的只是文字
替换,您需要的函数是 std::search
,以查找
要替换的文本和 std::string::replace
来执行
实际更换。您将面临的唯一实际问题:
std::string::replace
可以使您的迭代器无效。你可以
总是从字符串的开头开始搜索,但是这
可能会导致无限循环,如果替换文本包含
搜索字符串(例如 s/vector/std::vector/
)。
您应该转换从 std::search
返回的迭代器
到字符串中的偏移量 before 做替换 (offset
= iter - str.begin()
),然后将其转换回迭代器
(iter = str.begin() + offset + replacement.size()
)。 (这
添加 replacement.size()
是为了避免重新扫描文本
您刚刚插入,这可能会导致无限循环,因为
与上述相同的原因。)
关于c++ - 在 C++ 中实现查找和替换过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22696282/