Вопрос

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.

Другие советы

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;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top