Program to read lines from the keyboard and print only those containing a certain word.

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

#define MAX 50

int get_word(char s[], char word[], int begin)
{
int i;

for(i=begin;i<strlen(s);i++)
{
if(s[i]==' ') break;
word[i-begin]=s[i];
}
word[i-begin]='';

return i+1;
}

int occurs(char supstr[], char substr[])
{
char word[MAX];
int i,j,k;

//    printf("Asked to analyse: %s\n",supstr);

for(i=0;i<strlen(supstr);)
{
j=get_word(supstr,word,i);
//        printf("Next word read: %s\n",word);

if(!strcmp(word,substr)) return 1;

i=j;
}

return 0;
}

void readlines()
{
char lines[MAX][MAX], word[MAX];
int i=0, j=0;
char c;

printf("Enter the lines:\n");
while((c=getchar())!=EOF)
{
lines[i][j]=c;
if(c=='\n')
{
lines[i][j]='';
i++; j=0;
}
else j++;
}
lines[i][j]='';

printf("Enter the word to be read: ");
scanf("%s",word);

printf("The lines containing the word are:----------------------------------------------------\n");
for(j=0; j<i; j++)
if(occurs(lines[j], word)) printf("%s\n",lines[j]);
}

int main()
{
readlines();
return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s