I am wondering if it is possible to compare a char with an array with chars and find the index with the same characters
In python, you could use the index method:
colors = ['red', 'green', 'blue']
y = 'green'
x = colors.index(y)
print(x)
This would print:
1
How could you do this in C?
>Solution :
OP uses the word ‘similar’… The vagueness is unsettling.
To find an exact match implemented as a function, it is also possible to ‘borrow’ from the lesson given by *argv[]. If the list (in this case colours) has as its final element a NULL pointer, that fact can be used to advantage:
#include <stdio.h>
#include <string.h>
int index( char *arr[], char *trgt ) {
int i = 0;
while( arr[i] && strcmp( arr[i], trgt) ) i++;
return arr[i] ? i : -1;
}
int main() {
char *colors[] = { "red", "green", "blue", NULL };
printf( "%d\n", index( colors, "green" ) );
return 0;
}
One could/should also test function parameters have been supplied and are not themselves NULL values. This is left as an exercise for the reader.