简体   繁体   中英

searching multiple strings in a main string using strstr in C

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?

Store the answer, and call strstr() again, starting at the returned location + the length of the search string. Continue until it returns NULL .

Eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM