C语言 从行中提取短语



>我在文件中查找单词/短语.txt。

文件如下所示:

    apple tree 't' data
    apple 't' data
    apple pie 't' data
    Greek 't' data
    Holland ; Netherlands ; The Netherlands 't' data

我正在这个大文件中寻找char *word。当我有像NetherlandsThe Netherlands这样的词并且我想获取这些数据时,它会变得棘手。

我已经把问题分解成很小的部分。到目前为止,我知道文件有多少行,并且可以使用该信息来搜索该行。这些部分独立于下面的此部分工作。

file_lines = 12325;
// line_index[] every element corresponds to a line in to a line in the file.
char* buffer[256];
FILE fp = fopen(file.txt, "r") 
int i, j, k;
for(i = line_index[index_start]; i < line_index[index_end]; i++)
{
   fseek(fp, i, SEEK_SET);
   fgets(buffer, 256, fp);
   if(strstr(buffer, word) != NULL) // word is here
   {
     // having problems finding the word here
     for(j = 0; j < 256; j++)
       for(k = 0; k < 256; k++)
       {  
         if(buffer[k] == word[k])
          continue;
         if(buffer[k] == ' ')
          continue;
         if(buffer[k] == ';')
          break;
         if(buffer[k] == 't')
           break;
       }
   }
}

我最大的问题是确保单词/短语在该行中。我可以知道哪个潜在的行有这个词的实例,但是如果我正在寻找苹果,如果我没有正确搜索该行,我可能会得到苹果树。

请帮忙。

大致...

   char *tab = strchr(buffer, 't');
   if(tab) *tab = 0;
   if(strstr(buffer, word) != NULL) // word is here
   {
       char *token = strtok(buffer, ";");
       int found = 0;
       while(token) {
          // remove this printf later, but for now it will help you debug
          printf("'%s' vs '%s'n", word, token); 
          if(strcmp(word, token) == 0) {
              found = 1;
              break;
          }
          token = strtok(0, ";");
       }
       if(found) {
           if(tab == 0) {
              printf("No data for %sn", word);
           } else {
              printf("data is '%s'n", tab+1);
           }
       }

最新更新