string - C: counting number of words (need help fixing) -


i new c programming , trying write code counting number of words in string.here code counting number of codes.

    #include<stdio.h>      #include<string.h>     void main()      {          int count=0,i,len;          char str[100];          printf("enter sentence");          gets(str);          len=strlen(str);          for(i=0;i<=len;i++)          {              if(str[i]==' ')                count++;          }          printf("the number of words :\t%d",count+1);      } 

when input is:here 4 words works fine. gives output the number of words : 4

my question how handle "two consecutive spaces" between word, "space @ beginning" of input , "space @ last" of input.

instead of counting spaces, count first non-space character of each word.

#include<stdio.h>   int main()  {      int count=0;      char str[100];      printf("enter sentence");      gets(str);      char *cur= str;      (;;)     {         while (*cur == ' ')         {             cur++;         }          if (*cur == 0)         {             break;         }          count++;          while (*cur != 0 && *cur != ' ')         {             cur++;         }     }      printf("the number of words :\t%d",count);       return 0; } 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -