简体   繁体   中英

array iteration strstr in c

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:

  1. Return const char* from c() so that the caller cannot modify the resulting strings. All those strings are constant.
  2. Instead of the magic number 5 , which would become invalid if the array changed, use sizeof(list)/sizeof(list[0]) to compute the number of elements in the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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