【问题标题】:Checking if a string contains more than just keywords C++检查字符串是否包含不仅仅是关键字 C++
【发布时间】:2020-10-30 04:37:58
【问题描述】:

感谢您点击我的问题。

经过无数小时的搜索,我还没有找到解决方案,而且很难搜索到您不知道如何在搜索中正确表达的内容。请帮帮我,我将不胜感激。

字符串的数据如下:

std::string keyword 1 "Hello";
std::string keyword 2 "Ola";
std::string test = Keyword1+Keyword2+keyword2;

我想要实现的伪代码示例:

if(test.contains(more then the 2 keywords))

我想确保字符串除了上面的关键字之外还有其他文本。

【问题讨论】:

  • 不要标记C。你的代码是 C++

标签: c++ string format indexof


【解决方案1】:

您可以从数据中删除这些关键字的所有实例,然后查看剩下的内容。它的效率不是很高,但对于合理大小的输入应该无关紧要。

bool contains_more_than(std::vector<std::string> const& keywords, std::string sample) {
  for (std::string const& keyword: keywords) {
    size_t pos;
    while ((pos = sample.find(keyword)) != sample.npos) {
      sample.replace(pos, keyword.size(), "");
    }
  }
  return !sample.empty();
}

请注意,如果某个关键字是另一个关键字的子字符串,这可能会失败:

contains_more_than({"123", "12345"}, "12345") 返回 True。

为避免这种情况,您可以先按std::string::size 对关键字进行排序:

std::string(keywords.begin(), keywords.end(), 
    [](std::string const& s1, std::string const& s2) { 
        return s1.size() > s2.size(); 
    });

现在:

contains_more_than({"12345", "123"}, "12345") 返回 False

【讨论】:

    【解决方案2】:

    一种可能的解决方案:表示为regular expression,您正在测试字符串是否匹配^(Hello|Ola)*$。也就是说,整个字符串是否匹配任意数量的“Hello”和/或“Ola”重复(没有别的)?您可以使用regex standard library 来匹配 C++ 中的正则表达式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-19
      • 1970-01-01
      • 2014-07-16
      • 2014-05-07
      • 1970-01-01
      • 2014-03-02
      • 2011-01-25
      相关资源
      最近更新 更多