Home > Blockchain >  How to find index of same char in an array in C
How to find index of same char in an array in C

Time:12-18

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?

CodePudding user response:

To find an exact match (implemented as a function,) it is also possible to 'borrow' from the lesson given by char *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.

CodePudding user response:

You can use strcmp() to compare two strings character by character. If the strings are equal, the function returns 0.

#include <stdio.h>
#include <string.h>

int main() {
    char *colors[] = {"red", "green", "blue"};
    char *y = "green";
    int x = -1;
    for (int i = 0; i < 3; i  ) {
        if (strcmp(colors[i], y) == 0) {
            x = i;
            break;
        }
    }
    printf("%d\n", x);
    return 0;
}
  • Related