number of occurrences in a string

Course Queries Syllabus Queries 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Syllabus Queries related to Course Queries. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer 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

#include 
#include ngs.h>
int main()
{
    char sentence[100],word[20],temp[20];
    int i=0,j=0,occurrences=0;
    scanf("%[ ^\n]s",sentence);
    ntf">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;
    }
    ntf">printf("Number of Occurrences of the word are %d",occurrences);
    return 0;
}
profilepic.png
manpreet 2 years ago
  • The name of the header is string.h not strings.h.
  • use scanf(" %s",word); instead of fgets(word,20,stdin); to enter word.See the space before %s to consume whitespaces.
  • Also you have to add i++ after j=0 in your code,that is why it is running infinitely.

You code should be like this:

#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;
}

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.