C中的字符串搜索

时间:2014-09-23 04:41:10

标签: c arrays

在下面的代码中,strstr()函数似乎没有正确响应 - if()语句没有运行,因为strstr()始终给出空指针,尽管输入字符串(变量search_for)存在在数组中。经过几个小时的挫折,我现在放弃了。请帮忙!

#include <stdio.h>
#include <string.h>
char tracks[][80] = {
    "impossible",
    "how to grow strong",
    "love is in the air",
    "3 prophets of everland",
    "home"
};
void find_track(char search_for[])
{
    int i;
    for (i = 0; i < 5; i++)
    {
        if (strstr(tracks[i], search_for))
            printf("Track %i: %s", i, tracks[i]);
    }
}
int main(void)
{
    char search_for[80];
    printf("Search for: \n");
    fgets(search_for, 80, stdin);
    printf("%s", search_for);
    find_track(search_for);

    return 0;
}

2 个答案:

答案 0 :(得分:6)

您的输入字符串包含换行符\n。您可以使用调试器来避免数小时的挫败感。

答案 1 :(得分:0)

您可以使用'\n'覆盖null-terminating character来轻松删除#include <stdio.h> #include <string.h> char tracks[][80] = { "impossible", "how to grow strong", "love is in the air", "3 prophets of everland", "home" }; void find_track(char search_for[]) { int i; for (i = 0; i < 5; i++) { if (strstr(tracks[i], search_for)) printf("Track %i: %s", i, tracks[i]); } } int main(void) { char search_for[80]; size_t length = 0; printf("Search for: \n"); fgets(search_for, 80, stdin); length = strlen (search_for); search_for[length-1] = 0; printf("%s\n", search_for); find_track(search_for); printf ("\n"); return 0; } 字符:

$./bin/srchfor
Search for:
strong
strong
Track 1: how to grow strong

<强>输出:

{{1}}