Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //programme of counting number of words in a string
- char* remove_extra_spaces(char *s);
- int count_words(char *S);
- main()
- {
- char str[100];
- int no_of_words;
- printf("Enter a string\n");
- gets(str);
- printf(" \nString length with extra spaces is:%d",strlen(str));
- no_of_words=count_words(str);
- printf("\n Number of Words with extra spaces is : %d",no_of_words);
- strcpy(str,remove_extra_spaces(str));
- printf(" \nString length:%d",strlen(str));
- no_of_words=count_words(str);
- printf("\n Number of Words : %d",no_of_words);
- getch();
- }
- int count_words(char *s)
- {
- int i=0,count=0;
- while(*(s+i)){
- if(*(s+i)==' ')
- count++;
- i++;
- }
- return(count+1);
- }
- char* remove_extra_spaces(char *s)
- {
- char *p;
- int i=0,j=0;
- p=malloc(strlen(s)+1);
- while(*(s+i)){
- while(*(s+i)==' ')
- i++;
- while(*(s+i)!=' '&& *(s+i)!='\0')
- {
- *(p+j)=*(s+i);
- i++;j++;
- }if(*(s+i)=='\0'&& *(p+j-1)==' ')
- j--;
- *(p+j)=*(s+i);
- j++;
- }return(p);
- }
Add Comment
Please, Sign In to add comment