0

文字列が長すぎます。必要な単語をすべて検索して見つけたいと思います。たとえば、文字列内のすべての「リンゴ」の場所を見つけたいとします。どうやってそれを行うか教えてもらえますか?ありがとう

4

3 に答える 3

4

std::string::findC ++文字列を使用している場合、またはC文字列を使用している場合は、繰り返し適用std::strstrします。どちらの場合も、各反復で、最後の一致の後にn文字の検索を開始します。ここで、nは単語の長さです。

std::string str="one apple two apples three apples";
std::string search="apple";
for(std::string::size_type pos=0; pos<str.size(); pos+=search.size())
{
    pos=str.find(search, pos);
    if(pos==std::string::npos)
        break;
    std::cout<<"Match found at: "<<pos<<std::endl;
}

リンク

于 2012-07-06T12:53:55.687 に答える
2

std::string::find;を繰り返し呼び出すループを使用します。各反復で、最後のヒットを超えて検索を開始します。

std::vector<std::string::size_type> indicesOf( const std::string &s,
                                               const std::string &needle )
{
  std::vector<std::string::size_type> indices;
  std::string::size_type p = 0;
  while ( p < s.size() ) {
    std::string::size_type q = s.find( needle, p );
    if ( q == std::string::npos ) {
      break;
    }
    indices.push_back( q );
    p = q + needle.size(); // change needle.size() to 1 for overlapping matches
  }
  return indices;
}
于 2012-07-06T12:54:36.620 に答える
0
void findApples(const char* someString)
{
   const char* loc = NULL;
   while ((loc = strstr(someString, "apple")) != NULL) {
      // do something
      someString = loc + strlen("apple");
   }
}
于 2012-07-06T12:58:06.603 に答える