我有字符串说 "Dog is a kind of animal"
;
现在,如果我必须找到一个字符串,其中包含这些单词中的任何一个,而不是 Dog,如 Cat、Horse、Tiger、Lion,那么我必须给出字符串 OK 的状态。
我完全了解 string.find
函数,它将单个子字符串与字符串匹配。但在我的例子中,我必须用 30 种可能性检查字符串,例如猫、马、狮子 .... 30 种动物。
我不知道如何进行。
string line2 = "horse is a kind of animal" ;
const char* array[] = { "cat", "dog", "horse" };
for (unsigned int i = 0; i<= sizeof(array); i++)
{
size_t loc = line2.find( array[i], 0);
if( loc != string::npos)
{
std::cout <<"true"<<std::endl;
break;
}// end if
else
{
cout <<"not found"<< std::endl;
}
最佳答案
考虑使用许多可用的正则表达式(例如 google re2)库之一来搜索搜索词的并集 - 例如,(cat|dog|horse|...)
.这应该比简单地搜索每个子字符串更快,因为它只需要扫描一次字符串。
关于c++ - 查找字符串 : if found mark that string ok 中的任意子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4681411/