C:如何比较两个字符串并找到我需要的单词?

时间:2014-10-31 20:06:27

标签: c loops compare strcmp

它不完整,但它不会打印任何东西

char *fruit[] = {"rasberry", "cherry"};
char *veg[] = {"salad", "tomato"};
char word;


printf("Print a veg or a fruit \n");
scanf("%s", &word);


for (int i = 0; i < strcmp(fruit, veg ); i++)
{
    if (word == fruit[i])
        printf("Its fruit!");
}

如何比较?

1 个答案:

答案 0 :(得分:4)

在稍微澄清所需内容之后,请尝试以下方法:

    char *fruit[] = {"rasberry", "cherry"};
    char *veg[] = {"salad", "tomato"};
    char word[100]={0};


    printf("Print a veg or a fruit \n");
    scanf("%s", word);

    // Check fruit
    for (int i = 0; i < 2; i++)
    {
        if (strcmp(word,fruit[i])==0)
        {
            printf("Its fruit \n");
        }
    }
    // Check veg
    for (int i = 0; i < 2; i++)
    {
        if (strcmp(word,veg[i])==0)
        {
            printf("Its veg \n");
        }
    }