How to write below code in C? Also: is there any built in function for checking length of an array?
Python Code
x = [\'ab\', \'bc\'
A possible C implementation for Python's in
method could be
#include
int in(char **arr, int len, char *target) {
int i;
for(i = 0; i < len; i++) {
if(strncmp(arr[i], target, strlen(target)) == 0) {
return 1;
}
}
return 0;
}
int main() {
char *x[3] = { "ab", "bc", "cd" };
char *s = "ab";
if(in(x, 3, s)) {
// code
}
return 0;
}
Note that the use of strncmp
instead of strcmp
allows for easier comparison of string with different sizes. More about the both of them in their manpage.