Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find index of same char in an array in C

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading