bahadirtr
bahadirtr

Reputation: 53

Finding all wanted words in a string

I have a string which is too long, I want to find and locate all of the wanted words. For example I want to find the locations of all "apple"s in the string. Can you tell me how I do that? Thanks

Upvotes: 0

Views: 4775

Answers (3)

Matteo Italia
Matteo Italia

Reputation: 126777

Apply repeatedly std::string::find if you are using C++ strings, or std::strstr if you are using C strings; in both cases, at each iteration start to search n characters after the last match, where n is the length of your word.

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;
}

(link)

Upvotes: 4

Frerich Raabe
Frerich Raabe

Reputation: 94279

Use a loop which repeatedly calls std::string::find; on each iteration, you start finding beyond your last hit:

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;
}

Upvotes: 2

Nathan Parrish
Nathan Parrish

Reputation: 23

void findApples(const char* someString)
{
   const char* loc = NULL;
   while ((loc = strstr(someString, "apple")) != NULL) {
      // do something
      someString = loc + strlen("apple");
   }
}

Upvotes: 0

Related Questions