Reputation: 5
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.
#include <stdio.h>
#include <strings.h>
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");
fgets(word,20,stdin);
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;
}
printf("Number of Occurrences of the word are %d",occurrences);
return 0;
}
Upvotes: 0
Views: 96
Reputation: 3332
string.h
not strings.h
.scanf(" %s",word);
instead of fgets(word,20,stdin);
to enter
word
.See the space before %s
to consume whitespaces.i++
after j=0
in your code,that is why it is
running infinitely.You code should be like this:
#include <stdio.h>
#include <string.h> //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;
}
Upvotes: 1
Reputation: 16117
Change #include <strings.h>
to #include <string.h>
.
scanf("%[ ^\n]s", sentence);
won't function as you expect. To enter strings containing whitespace characters, you should use fgets(word, 20, stdin);
instead. Don't forget to handle the '\n'.
Remove that '\n' in word
.
BTW, the following code seems clearer to me:
#include <stdio.h>
#include <string.h>
int main()
{
char sentence[100], word[20];
int occurrences = 0, i = 0;
fgets(sentence, 100, stdin);
sentence[strcspn(sentence, "\n")] = '\0';
printf("Enter the word to be searched:\n");
fgets(word, 20, stdin);
word[strcspn(word, "\n")] = '\0';
while(strlen(word) + i <= strlen(sentence))
{
if(memcmp(word, sentence + i, strlen(word) - 1) == 0)
occurrences++;
i++;
}
printf("Number of Occurrences of the word are %d", occurrences);
return 0;
}
Upvotes: 0