c++ - 查找字符串 : if found mark that string ok 中的任意子字符串

标签 c++ string

我有字符串说 "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/

相关文章:

C++ 加速多个 substr() 或等效函数调用以解析大字符串

c++ - 在 CLion 中默认运行谷歌测试时出错

c++ - LNK1104 : cannot open file 'libboost_program_options-vc100-mt-sgd-1_56.lib'

c++ - IDE如何从头文件.h中找到共享库名.so

c++ - 如何简化多开关案例说明?

java - java加密解密中如何将String转换为byte[]?

c++ - 简单的数学表达式解析器 (c++)

c - 如何计算字符串中字符串的出现次数?

c# - 为什么我不能利用计算机中的 4GB RAM 来处理 C# 中少于 2GB 的信息?

javascript - Razor 代码在 JavaScript 字符串内创建新行