如何在行中返回单词的位置,C语言

时间:2015-12-08 11:55:02

标签: c algorithm

我在文本文件中找到单词的位置时遇到了一些问题。 问题是当用户输入要搜索的单词时,程序必须在此行中显示行号和位置。我的代码只显示行号,但我如何在这一行添加单词的位置?

P.S.I我认为我在搜索功能时使用的效率不高......

以下是代码:

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

int Search_in_File(char *str);
int main(int argc, const char * argv[]) {

    char word;

    printf("Please enter a word to search:\n");
    scanf("%s", &word);
    Search_in_File(&word);
}
int Search_in_File(char *str) {

    FILE *fp;
    int line_num = 1;
    int find_result = 0;
    char temp[1024];
    if((fp = fopen("/Users/S/Documents/Learning/C/text.txt","r")) == NULL) {
        return(1);
    }
    while(fgets(temp, 1024, fp) != NULL)
    {
        if((strstr(temp, str)) != NULL)
        {
            find_result++;
            printf("A match found on line: %d at position: \n", line_num);
        }
        line_num++;
    }

    if(find_result == 0) {
        printf("\nSorry, couldn't find a match.\n");
    }

    fclose(fp);

    return(0);
}

2 个答案:

答案 0 :(得分:1)

函数foo-bar-com返回指向行中单词出现的指针。指针算术可用于确定位置索引:

strstr()

然而,虽然这会找到找到的字符串的位置,但它并不知道什么构成了一个&#34;字&#34;。例如,它会找到&#34; man&#34; in&#34; mankind&#34;例如。

答案 1 :(得分:0)

char word;

您已声明char变量,但为了输入单词,您需要一个char数组。现在word只能存储一个字符。

声明足够的char数组 -

char word[50];
scanf("%49s", word);
Search_in_File(word);            // no need to pass address

编辑 -

对于获得排名的问题,您可以使用函数strtok代替strstr -

int position;
char *token;
while(fgets(temp, 1024, fp) != NULL)
{
    position =0;                      //set position to 0 in each iteration
    token=strtok(temp," ");           // search for space
    while(token!=NULL){
        position++;                   // as words are tokenized count spaces
        if(strcmp(token,str)==0){     //check for your word 
        find_result++;                       
        printf("A match found on line: %d at position: %d\n", line_num,position);  
      }      
     token=strtok(NULL," ");
    }
    line_num++;
}