[英]searching multiple strings in a main string using strstr in C
Currently, strstr
function returns the starting location of the found string; 当前,
strstr
函数返回找到的字符串的起始位置。 but I want to search for multiple strings and it should return me the location of the found string otherwise return NULL. 但我想搜索多个字符串,它应该返回找到的字符串的位置,否则返回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. 存储答案,然后从返回的位置+搜索字符串的长度开始再次调用
strstr()
。 Continue until it returns NULL
. 继续直到返回
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.