strtok - 如何将标记传递给 strstr() 以搜索相似的字符串?
问题描述
我正在尝试将包含空格的给定字符串拆分为多个字符串。然后我试图将这些字符串/令牌传递给 strstr() 以从给定文件中搜索类似的字符串。输出应在输出屏幕中显示匹配的字符串。我能够将字符串拆分为多个字符串,但我在 strstr() 中遇到了问题。它不是搜索并为我提供匹配的单词。这是代码:
#include<stdio.h>
#include<string.h>
#define MAXCHAR 20000
int main(){
FILE *fp,*fp2;
char str[MAXCHAR];
char str2[MAXCHAR];
char str3;
char delim[] = " ";
fp = fopen("blacklist.txt", "r");
if (fp == NULL)
{
printf("Cannot open %s\n", "blacklist.txt");
return 1;
}
fp2 = fopen("email.txt", "r");
if (fp2 == NULL)
{
printf("Cannot open %s\n", "email.txt");
return 1;
}
while (fgets(str2, MAXCHAR, fp2) != NULL){
char *ptr = strtok(str2, delim);
while(ptr != NULL){
printf("%s\n", ptr);
ptr = strtok(NULL, delim);
}
while (fgets(str, MAXCHAR, fp) != NULL){
rewind(fp2);
while (ptr != NULL){
char *p = strstr(str, ptr);
if (p != NULL && (p == str || p[-1] == '.'))
{
int n = strcspn(str, "\n");
int n2 = strcspn(ptr, "\n");
printf("domain matched on %.*s for %.*s\n", n2, ptr, n, str);
break;
}
}
}
}
fclose(fp);
fclose(fp2);
return 0;
}
解决方案
while
之后的循环永远不会进入,因为您rewind
确保这ptr
是null
(退出包含 的循环的唯一方法strtok
)。您正在拆分字符串并将它们打印出来,但程序无法访问拆分的字符串。
我认为像这样构造你的程序会更好:
while strtok != null
strcpy to an array and increment a counter for strings
while read a line
for each member of the array
strstr(line, string)
推荐阅读
- entity-framework - 如何设置我的模型关系以在 .NET Core 3.1 和 EF 中执行以下操作
- flutter - ListView 在另一个可滚动小部件中构建所有项目
- javascript - 从 Google Cloud Functions (JS) 中运行 Google Storage Command
- r - 马尔可夫链的R模拟
- regex - 如果某些数据依赖于另一个字段,如何使用正则表达式捕获某些数据?
- html - 在 flexbox 布局中展开中间项
- php - Cannot install WordPress error: "cannot connect to database"
- c - `atomic_compare_exchange_strong_explicit()` -- what do the various combinations of `success` and `failure` parameter do, when not equal?
- c# - 如何在构成 DataTable 中的第 3 列的 2 列值之间添加空格?
- r - Multiple plots gives a blank PDF, data dimension error