如何使String::Find(is)省略此项

How to make String::Find(is) omit this

本文关键字:何使 String Find is      更新时间:2023-10-16

如果我有一个列表,其中包含4个节点("this";"test example";"有点像";"a small"),并且我想找到每个具有"is"的字符串(该列表只有1个正)。这个话题已经被发布了很多次,我用这些来帮助我走到这一步。然而,我看不出我是如何从一个积极的结果中省略"这个"的。我可能会使用string::c_str,然后在缩减了更大的列表后自己找到它。或者有没有一种方法可以使用字符串::find_first_of?看来还有更好的办法。谢谢
编辑:我知道我可以省略一个特定的字符串,但我正在寻找更大的图片b/c我的列表相当大(例如:诗歌)。

for(it = phrases.begin(); it != phrases.end(); ++it)
{
    found = it->find(look);
    if(found != string::npos)
        cout << i++ << ". " << *it << endl;
    else
    {
        i++;
        insert++;
    }
}

只是想澄清一下:你在为什么而挣扎?

你想做的是检查你所发现的是一个单词(或短语)的开头还是单词(或词组)的结尾

即。检查是否:

  • found等于phrases.begin或者found之前的元素是空间
  • found之后的两个元素为空间OR phrases.end

编辑:您可以使用found访问找到的字符(将X替换为您正在查找的字符串的长度(look.length)

found = it->find(look);
if(found!=string::npos)
{
    if((found==0 || it->at(found-1)==' ')
        && (found==it->length-X || it->at(found+X)==' '))
    {
         // Actually found it
    }
} else {
    // Do whatever
}

我们可以使用boost正则表达式来搜索正则表达式。下面是一个示例代码。使用正则表达式可以创建复杂的seacrh模式。

#include <boost/regex.hpp> 
#include <string> 
#include <iostream> 
#include  <boost/tokenizer.hpp>
using namespace boost;
using namespace std;
int main()
{
  std::string list[4] = {"this","hi how r u ","is this fun is","no"};
  regex ex("^is"); 
  for(int x =0;x<4;++x)
  {
    string::const_iterator start, end;
    boost::char_separator<char> sep(" ");
    boost::tokenizer<boost::char_separator<char> > token(list[x],sep);
    cout << "Search string:  " << list[x] <<"n"<< endl;
    int x = 0;
    for(boost::tokenizer<boost::char_separator<char> >::iterator itr = token.begin();
        itr!=token.end();++itr)
    {
      start = (*itr).begin();
      end = (*itr).end();
      boost::match_results<std::string::const_iterator> what;
      boost::match_flag_type flags = boost::match_default;
      if(boost::regex_search(start, end, what, ex, flags))
      {
        ++x;
        cout << "Found--> " << what.str() << endl;
      }
    }
    
    cout<<"found pattern "<<x <<" times."<<endl<<endl;
  }
  return 0;
}

输出:

搜索字符串:此

找到模式0次。

搜索字符串:你好r u

找到模式0次。

搜索字符串:这是有趣的

已找到->已找到->被发现模式2次。

搜索字符串:无

找到模式0次。

我没有意识到你只想匹配"is"。您可以使用std::istringstream为您标记它:

std::string term("is");
for(std::list<std::string>::const_iterator it = phrases.begin();
    it != phrases.end(); ++it)
{
    std::istringstream ss(*it);
    std::string token;
    while(ss >> token)
    {
        if(token == term)
            std::cout << "Found " << token << "n";
    }
}