c ++ 有没有办法在字符串中找到句子

c++ Is there a way to find sentences within strings?

本文关键字:句子 字符串 有没有      更新时间:2023-10-16

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

"你觉得堆栈溢出怎么样?"

有没有办法在字符串中搜索"你做什么"?

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

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

use 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()返回相同的位置。若要搜索单个单词位置,请使用多个函数调用。

使用正则表达式

#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 库中的正则表达式是 boost::c++11 之前的正则表达式库)