如何查看字符串是否在字符串数组中 C

How to see if string is in array of strings C

C 中的整体数组让我很困惑,所以我完全不知道该怎么做。这是我正在尝试做的一个例子。

string hello = "hello";
string array[20] = {"e", "cat", "tree", "hello"};

for (int i = 0; i < 3; i++) {
    if (!strcmp(array[i], hello)) {
        printf("Hello is in the array");
    }
}

您的问题出在 for 循环退出条件,您的循环在 i == 3 之前停止,这是数组的最后一个索引。因为它永远不会碰到那个,所以它永远不会将您的字符串与 "hello" 所在的最后一个元素进行比较。

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

typedef char * string;

int main(int argc, char *argv[]) {
    string hello = "hello";
    string array[20] = {"e", "cat", "tree", "hello"};
    
    for (int i = 0; i < 4 /* not 3 */; i++) {
        if (!strcmp(array[i], hello)) {
            printf("Hello is in the array");
        }
    }
}

而且您刚刚亲身了解到为什么您永远不应该像这样对数组的计数进行硬编码。您不可避免地会编辑您的数组,而忘记更新您使用它的所有地方的硬编码计数。

试试这个,而不是:

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

typedef char * string;

int main(int argc, char *argv[]) {
    string hello = "hello";
    string array[] = {"e", "cat", "tree", "hello"};
    size_t array_count = sizeof(array) / sizeof(*array);

    for (int i = 0; i < array_count; i++) {
        if (!strcmp(array[i], hello)) {
            printf("Hello is in the array");
        }
    }
}