c++ - 在 C++ 中实现查找和替换过程

标签 c++ algorithm

只是为了好玩,我正在尝试编写一个类似于文字处理器的查找和替换程序。我想知道是否有人可以帮助我找出我做错了什么(我遇到了 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/

相关文章:

c++ - 使用 lambda 函数对 STL 容器进行排序

vba - Access 2016 VBA - 创建自定义控件集合,手动指定控件名称

c++ - "->"运算符在 C++ 中是什么意思?

C++11 operator""with double parameter

c++ - 为什么 stoi 比没有 -O3 的 stringstream 慢得多?

java - 解决 Java 中不明确的结构

java - 如何避免全局外部变量作为递归函数的输出

c++ - 如何使用动态编程自顶向下方法解决这个问题?

C++ 类成员 : Stack vs. 堆分配

c++ - 不能使用 boost::shared_mutex