从一行中提取一个短语

时间:2013-11-10 17:53:37

标签: c string

我在file.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;
       }

   }
}

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

请帮忙。

1 个答案:

答案 0 :(得分:2)

...大致

   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 %s\n", word);
           } else {
              printf("data is '%s'\n", tab+1);
           }
       }
相关问题