Reputation: 535
Currently, strstr
function returns the starting location of the found string; but I want to search for multiple strings and it should return me the location of the found string otherwise return NULL. Can anyone help how I can do that?
Upvotes: 0
Views: 4532
Reputation: 40145
E.g
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strpbrkEx(const char *str, const char **strs){
char *minp=(char*)-1, *p;
int len, lenmin;
if(NULL==str || NULL==strs)return NULL;
while(*strs){
p=strstr(str, *strs++);
if(p && minp > p)
minp = p;
}
if(minp == (char*)-1) return NULL;
return minp;
}
int main(){
const char *words[] = {"me","string","location", NULL};
const char *others[] = {"if","void","end", NULL};
const char data[]="it should return me the location of the found string otherwise return NULL.";
char *p;
p = strpbrkEx(data, words);
if(p)
printf("%s\n",p);
else
printf("(NULL)\n");
p = strpbrkEx(data, others);
if(p)
printf("%s\n",p);
else
printf("<NULL>\n");
return 0;
}
Upvotes: 1
Reputation: 399949
Store the answer, and call strstr()
again, starting at the returned location + the length of the search string. Continue until it returns NULL
.
Upvotes: 8