简体   繁体   English

如何在C中的数组中查找相同字符的索引

[英]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我想知道是否可以将 char 与带有 char 的数组进行比较并找到具有相同字符的索引

In python, you could use the index method:在 python 中,你可以使用 index 方法:

colors = ['red', 'green', 'blue']
y = 'green'
x = colors.index(y)
print(x)

This would print:这将打印:

1

How could you do this in C?你怎么能在 C 中做到这一点?

To find an exact match (implemented as a function,) it is also possible to 'borrow' from the lesson given by char *argv[] .要找到完全匹配(作为函数实现),也可以从char *argv[]给出的课程中“借用”。 If the list (in this case colours) has as its final element a NULL pointer, that fact can be used to advantage:如果列表(在本例中为颜色)的最后一个元素是 NULL 指针,则可以利用这一事实:

#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.还可以/应该测试已提供的函数参数,它们本身不是 NULL 值。 This is left as an exercise for the reader.这留给读者作为练习。

You can use strcmp() to compare two strings character by character.您可以使用strcmp()逐个字符地比较两个字符串。 If the strings are equal, the function returns 0.如果字符串相等,则函数返回 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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