Skip to content

Instantly share code, notes, and snippets.

@Manav1918
Created July 16, 2018 02:57
Show Gist options
  • Save Manav1918/d079828a76cba5680ef7d6ecbf0b163c to your computer and use it in GitHub Desktop.
Save Manav1918/d079828a76cba5680ef7d6ecbf0b163c to your computer and use it in GitHub Desktop.
count word in a string in c
//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);
}
@Manav1918
Copy link
Author

Thanx All of You

To learn more n more
with support of all of u

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment