I am trying to implement a strnstr function into C (strstr but it checks the length), for some reason it doesn't work (output is always no):
#include <stdio.h>
char *searchingFor = "stackdummy";
char *in = "la da
doo a da
now here comes the stack
ok there it was.
";
char *strnstr(char *s1, char *s2, int length) {
if(s1 == NULL || s2 == NULL) return NULL;
printf("searching
"%s"
for %.*s
", s1, length, s2);
char *ss1 = malloc(strlen(s1) + 1);
strcpy(ss1, s1);
char *ss2 = malloc(length + 1);
strncpy(ss2, s2, length);
char *result = strstr(ss1, ss2);
free(ss1);
free(ss2);
return result;
}
int main(void) {
printf("found: %s
", strnstr(in, searchingFor, 5) ? "yes" : "no");
printf("found: %s
", strnstr(in, searchingFor, 5) ? "yes" : "no");
printf("found: %s
", strnstr(in, searchingFor, 5) ? "yes" : "no");
return 0;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…