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# - 创建从左到右与从右到左部分连接的正确路径时出现问题

c++ - 从基类覆盖函数

c++ - 在 C++ 中编程 GUI

c# - 如何用不同的字符替换字符串中的每个数字?

c - 通过添加空格 (' ' ) 进行字符串操作,最大长度为 20

java - 如何让 Java 忽略字符串中的转义序列?

Android getResources().getStringArray() 变量

c++ - FastCGI 清理代码在 Windows 下不起作用

c++ - 在 C++ 中,一个函数有多少种调用方式?

c++ - 比特集比 bool 数组快吗?