首页 > 解决方案 > 如何使用strstr从char字符串中的数组中搜索单词

问题描述

我的问题是 strstr 函数、字符串和我想比较这个字符串的数组。

我的初始代码如下所示:

char t[255];
if (strstr(t, "test") || strstr(t, "test2") || strstr(t, "test3"))
{
    // found
}

其中t看起来像这样:

"xxxxxxx oooooo xxxxx testxxx test2xxxxxxxx xxxxxxxxxxxx"

此代码有效,但我想将所有搜索内容保存在一个数组中,所以我这样做了:

const char* list[3][1] =
{
    {"test"},
    {"test2"},
    {"test3"},
}

[...]

char t[255];
for (int i = 0; i < (sizeof(list)/sizeof(list)); i ++)
{
    if (strstr(t, list[i][0]))
    {
        // found
    }

t仍然看起来像:

"xxxxxxx oooooo xxxxx testxxx test2xxxxxxxx xxxxxxxxxxxx"

但由于某种原因,这种更改后的代码不起作用,即使它应该从数组中找到值,我该如何以正确的方式做到这一点?

预先感谢您的帮助

标签: c++

解决方案


sizeof(list)/sizeof(list)将始终为 1,因此您只检查列表中的第一个字符串。但是,仍然应该找到第一个字符串。你也不需要第二个数组索引——你可以只使用

const char *list[3] = { "test", "test1", "test2" };

int main() {
    char t[255] = "xxxxxxx oooooo xxxxx testxxx test2xxxxxxxx xxxxxxxxxxxx";

    for (int i = 0; i < sizeof(list)/sizeof(list[0]); ++i) {
        if (strstr(t, list[i])) {
            printf("found!\n");
            break; } }
}

推荐阅读