-
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;
}
-
> 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
}
-
...oh, ic...I think I would rather use "switch" to handle the cases...
by the way, great thx to Salem...