【问题标题】:Substring Replace Vector子串替换向量
【发布时间】:2015-07-14 15:14:38
【问题描述】:

这是一个最小的代码示例

我正在尝试创建一个要查找的子字符串数组,以便我可以用一个单词替换它们。在这种情况下,我将普通问候语改为简单的“嗨”。

问题是当我运行代码时出现错误。

错误:没有匹配的函数可以调用 'std::vector >::push_back(const char [4], const char [4], const char [3])'

如果有人可以帮助我理解为什么会发生此错误并提出一个完美的解决方案。

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
#include <ctime>
#include <vector>

    vector<string> hiWord;
    hiWord.push_back("hey", "sup", "yo");
    for (const auto& word : hiWord){
    while (true) {
     index = r.find(word);
     if (index == string::npos)
        break;
     r.replace(index, word.size(), "hi");
  }
}

【问题讨论】:

  • 代码很难阅读,请格式化。
  • 指定问题,以便清楚您想要做什么。
  • 这是一个练习吗?还是最小的(代码)示例?照原样,这个问题可能有很多答案,但没有一个很有意义。例如,计算字符串中的单词数并多次返回“hi”也适用于您的示例。
  • 这是一个最小的代码示例。

标签: c++ vector replace substring


【解决方案1】:

您可能希望从创建要搜索和替换的字符串的向量开始:

vector<string> searchWords = {"hey", "hello", "sup"};

然后使用循环运行你已经写好的代码,例如

for (const auto& word : searchWords) {
  while (true) {
     index = r.find(word);
     if (index == string::npos)
        break;
     r.replace(index, word.size(), "hi");
  }
}

【讨论】:

  • 向量的声明不起作用。它给了我错误“错误:在 C++98 中'seachWords'必须由构造函数初始化,而不是由'{...}'”你有什么理由吗?
  • 是的,我编写它的方式使用 C++11 语法。如果你的编译器支持 C++11,你应该设置它来使用它。否则,您可以将该行拆分为单独的声明并像这样调用vector::push_backvector&lt;string&gt; searchWords;searchWords.push_back("hey"); 等...
  • 我的答案中的 ranged-for 循环也是 C++11 构造,因此您可能也必须将其转换为旧样式。
  • 好的,我已经切换了代码,但它现在给了我一个新错误,即“错误:没有要调用的匹配函数”。
  • 您能否发布新代码作为对原始帖子的修改?
【解决方案2】:

您可以通过创建自己的替换函数来完成此操作

void replace(std::string &str, const std::string &token, const std::string &newToken)
{
    size_t index = 0;
    while((index = r.find(token, index)) != std::string::npos)
    {
        r.replace(index, token.length(), newToken);
    }
}

//You can overload this function to take a vector, Array or whathever you like
void replace(std::string &str, const std::vector<std::string> &tokens, const std::string &newToken)
{
    for(size_t i = 0; i < tokens.size(); ++i)
    {
        replace(str, tokens[i], newToken);
    }
}

//And you can call it like this
string r("hey hello sup");

replace(r, "hey", "hi");
replace(r, {"hello", "sup"}, "hi");

【讨论】:

  • 这是一个好主意,但可以在另一个实例中工作,但变量 r 不能像在您的代码中那样替换。它仍然保存着其他不能丢失的信息。
  • @PlayerCoder 所以你需要让你的问题更清楚。我实际上没有得到你想要达到的目标!
  • 这是真的,对不起。只是我被告知要提供相关信息,我认为我在问题中提出的所有内容都是唯一的。
猜你喜欢
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
相关资源
最近更新 更多