【问题标题】:c++ Is there a way to find sentences within strings?c ++有没有办法在字符串中查找句子?
【发布时间】:2016-01-28 12:29:25
【问题描述】:

我正在尝试识别用户定义的字符串中的某些短语,但到目前为止只能得到一个单词。 例如,如果我有句子:

“你怎么看堆栈溢出?”

有没有办法在字符串中搜索“What do you”?

我知道您可以使用 find 功能检索单个单词,但是当尝试获取所有三个单词时,它会卡住并且只能搜索第一个。

有没有办法在另一个字符串中搜索整个字符串?

【问题讨论】:

  • 请出示您的代码
  • 在字符串中搜索子字符串,使用std::string::find
  • “我知道你可以用 find 检索一个单词” 嗯??您可以使用std::string::find() 找到任何内容。如果您的问题是字符串中的空格数量不同,您可能需要std::regex
  • 如果我正确理解您的问题,这是一个重要的问题。它需要一些语言、语法等方面的知识。如果你真的想在haystack 中找到needle,请像其他人提到的那样使用std::string::find

标签: c++ string pattern-matching


【解决方案1】:

使用 str.find()

size_t find (const string& str, size_t pos = 0)

它的返回值是子串的起始位置。您可以通过执行返回 str::npos:

的简单布尔测试来测试您要查找的字符串 是否包含在主字符串中
string str = "What do you think of stack overflow?";
if (str.find("What do you") != str::npos) // is contained

第二个参数可用于限制从某个字符串位置开始搜索。

OP 问题提到它在尝试查找三字字符串时遇到问题。实际上,我相信您误解了返回值。碰巧单个词搜索“What”和字符串“What do you”的返回具有巧合的起始位置,因此 str.find() 返回相同。要搜索单个单词的位置,请使用多个函数调用。

【讨论】:

  • 你说得对,我一直读错回复,谢谢
【解决方案2】:

使用regular expressions

#include <iostream>
#include <string>
#include <regex>

int main ()
{
  std::string s ("What do you think of stack overflow?");
  std::smatch m;
  std::regex e ("\\bWhat do you think\\b");

  std::cout << "The following matches and submatches were found:" << std::endl;

  while (std::regex_search (s,m,e)) {
    for (auto x:m) std::cout << x << " ";
    std::cout << std::endl;
    s = m.suffix().str();
  }

  return 0;
}

您还可以找到使用 boost 实现的通配符(std 库中的正则表达式是 c++11 之前的 boost::regex 库)there

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-18
    • 2020-03-01
    • 2018-04-17
    • 2020-01-31
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多