Monday, 11 March 2019

C program to find number of words or tokens in a string

Following program returns the number of words contained in a string.Suppose, we have a string str="Computer Science & Engineering",functions return 4.

#include<stdio.h>
int main(void)
{
  char str[]="Computer Science & Engineering";
  int t=1,i,n=0;
  i=0;
  while(str[i]!='\0')
  {
      if(i==0)
      while(str[i]==' ')
           i++;
      if(str[i]==' ')
        t++;
    while(str[i]==' ')
         i++;
       i++;
  }
  printf("\nTokens=%d\n",t);
  return 0;
}

Output:

Please comment if you find anything incorrect, or you want to improve the topic discussed above.

No comments:

Post a Comment