Question

How do I write a C program that finds how many times a word is used...

How do I write a C program that finds how many times a word is used in a string and prints the result. The string is hardcoded. How do I also make it print the hashes?

For instance: String: " Dog Cat Owl Ferret Rabbit Cat Dolphin Penguin Cat"

Word 1: Owl

Word 2: Cat

Desired Output:

Owl- 1 time(s)

Cat: 3 time(s)

Owl- #

Cat-###

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <stdio.h>
#include <string.h>

/* Function declaration */
int counting(char * s, char * w);

int main()
{
char str[500];
char substr[100];
int count;
/* Input string and word from user */
printf("Enter main string: ");
fgets(str,500, stdin);
  
/*do while loop to search for words continuously*/
while(1){
int k=0;
printf("Enter word to search: ");
/*scanf("%s",&substr);*/
gets(substr);
  
count = counting(str, substr);
printf("%s -",substr);
  
for(k=0;k<count;k++)
{
printf("#");
}
printf("\n");
}
  
  
return 0;
}


/**
* Get, total number of occurrences of a word in a string
*/
int counting(char *s,char *w)
{
int n,a[1000],i,j,k=0,l,count=0,t=0;
for(i=0;s[i];i++)
{
   if(s[i]==' ')
   {
       a[k++]=i;
       }
   }
   a[k++]=i;
   j=0;
   for(i=0;i<k;i++)
   {
       n=a[i]-j;
       if(n==strlen(w))
       {
           t=0;
           for(l=0;w[l];l++)
           {
               if(s[l+j]==w[l])
               {
                   t++;
               }
           }
           if(t==strlen(w))
       {
               count++;
           }
       }
  
       j=a[i]+1;
   }
     
return count;
}

Add a comment
Know the answer?
Add Answer to:
How do I write a C program that finds how many times a word is used...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT