繁体   English   中英

在C中使用strstr在主字符串中搜索多个字符串

[英]searching multiple strings in a main string using strstr in C

当前, strstr函数返回找到的字符串的起始位置。 但我想搜索多个字符串,它应该返回找到的字符串的位置,否则返回NULL。 谁能帮助我做到这一点?

存储答案,然后从返回的位置+搜索字符串的长度开始再次调用strstr() 继续直到返回NULL为止。

例如

#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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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