問題
【問題描述】
從文件中查找包含給定字符串的行。
【輸入形式】
從標準輸入中分兩行分別輸入被查找的文件及要查找的字符串(中間不含空格)。
【輸出形式】
在屏幕上輸出文件中包含給定字符串的行。
【樣例輸入】
在鍵盤輸入如下文件名及字符串:
test.txt
the
文件test.txt內容如下:
Now is the time
for all good
men to come to the aid
of their party
【樣例輸出】
屏幕輸出爲:
this is the time
men to come to the aid
of their party
算法分析
設 int index ( char s[ ], char t[ ] )函數用來在字符串s中查找字符串t。若找到則反回t在s中出現的位置,否則返回-1。其主要查找算法如下:
for(i=0; s[i] != '\0'; i++)
for(j=i,k=0; t[k] != '\0'; j++,k++)
s[j]和t[k]進行比較 //不同時break;找到的條件是:t[k]==‘\0’
主要算法如下:
設變量filename,s,line分別用於存儲文件名、查找串及文件中一行;
從標準輸入中讀入文件名和要查找的串到filename和s中;
以讀方式打開文件filename;
while 文件中還有內容時讀一行到line中
如果 index(line, s) >= 0
輸出line;
算法實現
#include <stdio.h>
#define MAXLINE 1000
int index(char s[ ], char t[ ]);
int main( )
{
char filename[64], s[81], line[MAXLINE];
FILE *fp;
scanf("%s", filename);
scanf("%s", s);
if((fp = fopen(filename, "r")) == NULL){
printf("Can't open file %s!\n", filename);
return 1;
}
while(fgets(line, 81, fp) != NULL)
if(index(line, s) >= 0)
printf("%s", line);
return 0;
}
int index(char s[ ], char t[ ])
{
int i, j, k;
for(i =0; s[i] != '\0'; i++){
for(j=i,k=0;t[k]!='\0'&&s[j]== t[k]; j++,k++)
;
if(t[k] == '\0')
return ( i);
}
return ( -1);
}