c++ - 如何使用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"
但由于某种原因,这种更改后的代码不起作用,即使它应该从数组中找到值,我该如何以正确的方式做到这一点?
预先感谢您的帮助
解决方案
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; } }
}
推荐阅读
- machine-learning - 使用 Keras 加快模型评估速度
- rust - 如何不将进度条数据与其他输出混合?
- node.js - 服务器发送的事件没有从 React 和 NodeJs 的流中接收消息
- python - 找不到 Django 博客页面 (404) - 没有帖子与给定的查询匹配
- bixby - 当 Bixby 胶囊启动时调用特定操作
- dask - 将 NFS 与 Dask 工作人员一起使用
- reactjs - 如何使用打字稿为 HOC 编写通用类型?
- django - 在 Django 模板中聚合相关的整数字段值
- python - 读取txt文件中的关键字,并打印添加文本+关键字
- variables - 在商店页面显示最大可变价格