c - 如何在屏幕上显示搜索到的字符串?

标签 c for-loop strstr

所以,我要做的是让用户搜索奶酪并将其显示在屏幕上。我遇到了后者的麻烦。我似乎无法显示字符串,但我的代码仍在运行。这是我的代码:

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

    char cheeses[][20] = {
        "Cheddar",
        "White Cheddar",
        "Colby Jack",
        "Gouda",
        "Blue Cheese",
        "Gorgonzola",
        "Asiago", 
        "Limburger",
        "Feta",
        "Brie",
        "Goat",
    };

        void find_cheese(const char *search_for)
    {
        int i;
        for (i = 0; i < 5; i++) {
            if (strstr(cheeses[i], search_for))
                printf("Cheese %i: '%s'\n", i, cheeses[i]);
        }
    }

int main()
    {
        char search_for[20];
        printf("Search for: ");
        fgets(search_for, 20, stdin);
        find_cheese(search_for);
        return 0;
    }

那么在这种情况下我该怎么办。我想要它,以便您可以输入“Lim”并让它显示 Limburger(将来它将能够显示有关奶酪的信息)。我将如何做到这一点?

最佳答案

看起来不错,但您只先搜索 5 个,而 Limburger 太接近列表的末尾了。

这种类型的代码最好用“哨兵”来解决,即用于表示列表已结束的特殊标记。对于字符串,您可以将数组表示为指向字符串的指针数组而不是固定大小的数组,然后使用 NULL 作为标记是很自然的。

数组会变成:

const char *cheeses[] = { "Cheddar", "White Cheddar", "Colby Jack",
          /* ... rest of the cheeses ... */
          NULL
};

然后你可以这样写搜索循环:

int i;

for( i = 0; cheeses[i] != NULL; ++i )
{
  /* Test and handling code here, against cheeses[i] just like before. */
}

关于c - 如何在屏幕上显示搜索到的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12823859/

相关文章:

java - 通过 cygwin 使用 JNA 从 Java8 调用 C

c - 如何使控制台应用程序接收 100,000 个整数的输入

c - xlib 获取图标数据以在窗口上绘制

Java循环遍历字母表中的所有字母加上'

C:从 u_char* 解析子字符串

yacc 文件中无法识别的 c 语句

javascript - 对象在一个参数内传递多个参数

java - 错误: incompatible types Object Could not be converted [ArrayList]

c - strstr C函数运行异常

c - strstr() - C 库函数在字符串 (haystack) 中找不到字符串 (needle)