I was wondering if it's safe to do the following iteration to find the first occurrence of str within the array or if there is a better way. Thanks
#include <stdio.h>
#include <string.h>
const char * list[] = {"One","Two","Three","Four","Five"};
char *c(char * str) {
int i;
for (i = 0; i < 5; i++) {
if (strstr(str, list[i]) != NULL) return list[i];
}
return "Not Found";
}
int main() {
char str[] = "This is a simple string of hshhs wo a char";
printf("%s", c(str));
return 0;
}
Yes it's "safe" in the sense that the above code will work and there's no easy way to break it .
A little fix-up however would be more robust:
const char*
from c()
so that the caller cannot modify the resulting strings. All those strings are constant.5
, which would become invalid if the array changed, use sizeof(list)/sizeof(list[0])
to compute the number of elements in the list.