- The name of the header is
string.h
notstrings.h
. - use
scanf(" %s",word);
instead offgets(word,20,stdin);
to enterword
.See the space before%s
to consume whitespaces. - Also you have to add
i++
afterj=0
in your code,that is why it is running infinitely.
#include dio.h>
#include //fix 1
int main()
{
char sentence[100],word[20],temp[20];
int i=0,j=0,occurrences=0;
scanf("%[^\n]s",sentence);
printf("Enter the word to be searched:\n");
scanf(" %s",word); //fix 2
while(sentence[i]!='\0')
{
while(sentence[i]!=' '&&sentence[i]!='\0')
{
temp[j++]=sentence[i];
i++;
}
temp[j]='\0';
if((strcmp(temp,word))==0)
occurrences++;
if(sentence[i]==' ')
{
j=0;i++; //fix 3
}
}
printf("Number of Occurrences of the word are %d",occurrences);
return 0;
}
manpreet
Best Answer
2 years ago
Given a array string, I have to enter a word and find the occurrences of the word in the string, however I cannot enter the word for which I need to find the occurrence. I cannot use pointers as it hasn't been covered in the syllabus. Help would be appreciated