Starting address of words in a line

Problem statement
Write a c program to do the following
Consider the interface of a recursive function:
int wordIndex(char *x, int ind[]).
It takes a string and an int array as parameters.
It returns the word count(i.e. the number of words in that line). The int array after
return will hold the starting indexes of words in
the string.
For Example 
Consider the string
"This string has five words".
Your program should say that this line contains 5 words,and starting address of words are 1,5,...

#include<stdio.h>
int wordindex(char temp[],int counter[]);
int main()
{
  char line[50];
  int counter[20]={0},ans,y,i;
  printf("enter the string \n");
  scanf("%[^'\n']",line);
  ans=wordindex(line,counter+1); // counter[0] is reserved for 0
  printf("%d starting points found \n and the index are",ans+1);
  for(i=0;i<ans+1;i++)
    {
      printf("%d ",counter[i]+1);
    }
  scanf("%d",&y);
  return 0;
}
int wordindex(char temp[],int counter[])
{
  if(*temp=='\0')
    {
      return 0;
    }
  else if(*temp==' ')
    {
      *counter=*counter+1;
      *(counter+1)=*counter;
      return 1+wordindex(temp+1,counter+1);
    }
  else
    {
      *counter=*counter+1;
      return wordindex(temp+1,counter);
    }
}      

No comments:

Post a Comment