#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
 char str[80],temp[80],word[20];
 int i,j=0,c=0;
 gets(str);
 gets(word);
 strcat(str," ");
 for(i=0;str[i]!='\0';i++)
  {
    if(str[i]!=' ')
     {
      temp[j]=str[i];
      j++;
     }
    else
     {
       temp[j]='\0';
       if(strcmp(temp,word)==0)
        c++;
     }
  }
 printf("%d",c);
getch();
}

now my problem is that it is counting only the first word.. what's wrong with the code??

Edited 6 Years Ago by __avd: Added [code] tags.

You put in a string of words as ONE string. The strcat() I don't believe was necessary or desirable. But you're expecting an end of string char, for every word, and there will not be one for every word. There is just one (originally) for the entire string of words.

Change your logic to look for the space, and then if your letters have matched since the last space was reached, you have a matching word.

#include<stdio.h>
#include<conio.h>
#include<string.h>
char str[200];
void main()
{
 void opx(char *);
 char str1[20];
 int x=0,y=0,i;
 printf("enter the string");
 gets(str);
 while(str[y]!=0 && y<strlen(str))
 {

  for(i=0;str[i]!='\0';i++)
  {
   str1[i]='\0';
  }
   while(str[y]!=' '&& y<strlen(str) && str[y]!='\0')
   {
     str1[x]=str[y];
     x++;
     y++;
   }
  if(str1[0]!='\0')
  {
   opx(str1);
  }
  x=0;
  y++;
 }
 getch();
}
void opx(char *word)
{
  char s;
  int i,j,count,c,h;
  i=j=0;
  count=0;
  c=strlen(word);
  while(str[i]!='\0' && i<strlen(str))
  {
   h=i;
   while(str[i]!=' '&& i<strlen(str) && str[i]!='?'&& str[i]!='.'&& str[i]!=',')
   {
    if(j==c && str[i]!=' '&& str[i]!='?' && str[i]!='.' && str[i]!=',')
    {
        j++;
    }
        if(str[i]==word[j] && str[i]!=' '&& str[i]!='?' && str[i]!='.' && str[i]!=',')
        j++;
        i++;
   }
    if(c==j)
    {
    count++;
    while(str[h]!=' ' && str[h]!='\0')
    {
         if(str[h]=='\0')
           {
        str[h]='\0';
           }
           else
           str[h]=' ';
           h++;
    }
    }
    j=0;
    i++;
 }
 printf("\n%s word occurs %d  times",word,count);

}

it works jst check it out!

This article has been dead for over six months. Start a new discussion instead.