Lashhanth Dhevaraju
Lashhanth Dhevaraju

Reputation: 5

number of occurrences in a string in C

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

Answers (2)

Rajeev Singh
Rajeev Singh

Reputation: 3332

  • 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 <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

nalzok
nalzok

Reputation: 16117

  1. Change #include <strings.h> to #include <string.h>.

  2. 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'.

  3. 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

Related Questions