EmbLogic's Blog

I want code optimization

Dear All!!

I have done this assignment but Ain’t satisfying. I want code optimization.

Assignment No. =>005_16(Q.No.17)  Write a program to find the number of times that a given word(i.g a short string) occurs in a sentence (i.e. a long string!). Read data from standard input. The first line is a single word, which is followed by general text on the second line. Read both up to a newline character, and insert a terminating null before processing. Typical output should be:

The word is “the”. //should be any word

The sentence is “the cat sat on the mat”. //can be any sentence

The word occurs 2 times.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int search(char *, char *);
int main()
{
/*’word’ input from user*/
char *ch=0;
int i;
printf(“Enter \’word\’\n”);
ch=(char *)malloc(sizeof(char)*100);
fgets(ch,100,stdin);
/*input String*/
printf(“Enter \’Sentence\’\n”);
char *str=0;
str=(char *)malloc(sizeof(char)*100);
fgets(str,100,stdin);
i=strlen(str);–i;
str[i] = ‘ ‘;++i;
str[i] = ”;
search(ch,str);
return 0;
}
int search(char *ch, char *str)
{
int i=0,j=0,count=0;
while((*(str+i))!=”)
{
if(((*(str+i)) == (*(ch+j))) || (((*(str+i)) == ‘ ‘) && ((*(ch+j)) == 10)))
{
if(((*(str+i))== ‘ ‘) && ((*(ch+j))==10))
{
count++;
j=-1;
}
j++;
}
else
{
for(i;(*(str+i) != ‘ ‘);i++)
if((*(str+i))==10)
break;
}
i++;
}
printf(“The word occurs %d times \n”,count);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>