c ++ 有没有办法在字符串中找到句子
c++ Is there a way to find sentences within strings?
我正在尝试识别用户定义的字符串中的某些短语,但到目前为止只能得到一个单词。例如,如果我有这样的句子:
"你觉得堆栈溢出怎么样?"
有没有办法在字符串中搜索"你做什么"?
我知道您可以使用查找功能检索单个单词,但是当尝试获取所有三个单词时,它会卡住并且只能搜索第一个单词。
有没有办法在另一个字符串中搜索整个字符串?
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 之前的正则表达式库)
相关文章:
- 如何输入每个单词在字符串数组中的句子,直到用户按Enter键
- 句子与字符串向量中的每个句子的相似程度
- 使用 getline 和字符串流检查句子中的单词是否在文件中
- C 如何在字符串中大写每个句子/行的第一个单词
- 如何使用 c++ 反转句子字符串中的每个单词,例如"I love computer science"
- 如何在字符串中选择句子的一部分 (C++)
- C++ 如果要替换的句子具有"+"符号,则替换字符串功能不起作用
- 根据这些字符串输入在句子中的位置对这些字符串输入进行排序的更快方法是什么
- 对于字符串/句子不起作用的最接近的匹配算法
- 句子的句子时,有哪种类型的指标可以在字符串的末端进行
- 尝试编写代码来更正由内而外编写的字符串句子
- c ++ 有没有办法在字符串中找到句子
- C++ - 使用 stringstream 对象从外部 txt 文件中的句子中读取字符串和整数
- 句子变成单词c++字符串
- 检查字符串是否包含英语句子
- 如何计算字符串中的句子数
- 输入句子并将其转换为字符串
- 我想从字符串句子中取出单词并在 C++ 中得到此错误
- C++使用C字符串计算文件中的字符、单词、句子
- 如何存储一个完整的句子与空白的字符串在cpp