Thread: Question about strstr()

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    11

    Question about strstr()

    I want to find the occurances of a list of words(eg: MTR, UK, USA, MAC, MS, DHL) in an array, thus, I make use of a strstr() function. However, the function can only accept matching one element a time, how can I match a list of word by using strstr()?

    Here's my code

    Code:
    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <stdlib.h>
    
    using std::cin;
    using std::cout;
    using std::endl;
    
    int main()
    {
    
       char str[] = "Making Simple Things Simple. With todays programming languages, most people find it very difficult to do even simple things.";
       char *pch;
       char *abc;
       pch = &str[0];
    
       while ( pch != NULL )
       {
          pch = strstr (pch,"simple");   // for instance: How can I match "simple" and "difficult" by using only one strstr expression at a time?
          if ( pch != NULL )
          {
             cout << pch;
             pch = &pch[0+6];
          }
       }
    
       system("PAUSE");
       return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    > How can I match "simple" and "difficult" by using only one strstr expression at a time?
    You can't - so you need to call strstr() twice, once for each string
    Code:
    char *a = strstr( pch, "simple" );
    char *b = strstr( pch, "difficult" );
    if ( a != NULL && b != NULL ) {
      if ( a < b ) {
        // found simple first
      } else {
        // found difficult first
      }
    } else {
      // either (or both) are NULL - handle cases
    }

  3. #3
    Registered User
    Join Date
    May 2004
    Posts
    11
    ...oh, ic...I think I would rather use "switch" to handle the cases...
    by the way, great thx to Salem...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  2. strstr() question
    By blue_gene in forum C Programming
    Replies: 12
    Last Post: 04-15-2004, 10:22 PM
  3. Question About Finding a Word and Replacing It
    By Zildjian in forum C Programming
    Replies: 3
    Last Post: 09-23-2003, 08:50 AM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM