Guest User

Untitled

a guest
Jul 15th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. //programme of counting number of words in a string
  2. char* remove_extra_spaces(char *s);
  3. int count_words(char *S);
  4. main()
  5. {
  6. char str[100];
  7. int no_of_words;
  8. printf("Enter a string\n");
  9. gets(str);
  10. printf(" \nString length with extra spaces is:%d",strlen(str));
  11. no_of_words=count_words(str);
  12. printf("\n Number of Words with extra spaces is : %d",no_of_words);
  13.  
  14.  
  15. strcpy(str,remove_extra_spaces(str));
  16. printf(" \nString length:%d",strlen(str));
  17. no_of_words=count_words(str);
  18. printf("\n Number of Words : %d",no_of_words);
  19. getch();
  20. }
  21. int count_words(char *s)
  22. {
  23. int i=0,count=0;
  24. while(*(s+i)){
  25. if(*(s+i)==' ')
  26. count++;
  27. i++;
  28. }
  29. return(count+1);
  30. }
  31. char* remove_extra_spaces(char *s)
  32. {
  33. char *p;
  34. int i=0,j=0;
  35. p=malloc(strlen(s)+1);
  36. while(*(s+i)){
  37. while(*(s+i)==' ')
  38. i++;
  39. while(*(s+i)!=' '&& *(s+i)!='\0')
  40. {
  41. *(p+j)=*(s+i);
  42. i++;j++;
  43. }if(*(s+i)=='\0'&& *(p+j-1)==' ')
  44. j--;
  45. *(p+j)=*(s+i);
  46. j++;
  47.  
  48. }return(p);
  49. }
Add Comment
Please, Sign In to add comment