简体   繁体   English

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

[英]How to see if string is in array of strings C

Overall arrays in C are very confusing to me, so I have absolutely no idea of how to do this.总体而言,C 中的 arrays 让我非常困惑,所以我完全不知道该怎么做。 Here is an example of what I am trying to do.这是我正在尝试做的一个例子。

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");
    }
}

Your issue is in the for loops exit condition, your loops stops before i == 3 , which is the last index of your array.您的问题在于for循环退出条件,您的循环在i == 3之前停止,这是数组的最后一个索引。 Since it never hits that, it never compares your string against the last element, where the "hello" is.因为它从来没有达到这个目标,所以它永远不会将您的字符串与"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");
        }
    }
}

And you just learned, first hand, why you should never hard code the count of an array like this.你刚刚了解到,为什么你永远不应该像这样对数组的计数进行硬编码。 It's inevitable that you'll edit your array, and forget to update the hard-coded count in all the places where you used it.您将不可避免地编辑您的数组,并忘记在您使用它的所有地方更新硬编码计数。

Try this, instead:试试这个,而不是:

#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");
        }
    }
}

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

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