首页 > 解决方案 > 如何将标记传递给 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;
    }

标签: strtokstrstr

解决方案


while之后的循环永远不会进入,因为您rewind确保这ptrnull(退出包含 的循环的唯一方法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)

推荐阅读