我试图识别用户定义字符串中的某些短语,但到目前为止只能获得一个单词。 例如,如果我有句子:
"您如何看待堆栈溢出?"
有没有办法搜索"你是什么"在字符串中?
我知道你可以使用find函数检索单个单词但是当试图获取所有三个单词时它会卡住并且只能搜索第一个单词。
有没有办法在另一个字符串中搜索整个字符串?
答案 0 :(得分:0)
使用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问题提到它试图找到一个三字的字符串。实际上,我相信你错误地解释了回报价值。碰巧单词搜索的回报"什么"和字符串"你是什么"有巧合的起始位置,因此str.find()返回相同的。要搜索单个单词的位置,请使用多个函数调用。
答案 1 :(得分:0)
#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库中的regex是c ++ 11之前的boost :: regex库)there