Check The Programming Section
We always take very common approach to count number of words or sub-string in a string by looking for a space between two words. If we found a space between two words it is considered that a word is read by the program. Consider the following inputs:
#include<stdio.h>
int main(){
char line[100];
printf("Enter any line::");
scanf("%[^\n]s",line);
int i = 0;
int count = 0;
while(line[i]!='\0'){
if(line[i]==' ') count++;
i++;
}
printf("The number of words in %s is %d",line,count+1);
}
For the above program, we need to be careful while giving input and following points need to consider:
string should not contain any leading space
string should not contain any trailing space
between two words exactly one space is there
At last we add 1 with the number of spaces present in a line. What if, we give any leading and trailing space or an extra space is given between two words. Consider the following inputs:
The above program counts wrong number of words in a string if it contains any extra space or has atleast one leading or trailing space. We need to taken care all such case and the above program is re-written as follows:
#include<stdio.h>
int countWords(char line[]){
int count = 0;
int i = 0;
while(line[i]!='\0'){
if(line[i]!=' ' && line[i+1]==' ')
count++;
else if(line[i]!=' ' && line[i+1]=='\0')
count++;
i++;
}
return count;
}
int main(){
char line[100];
printf("Enter any line::");
scanf("%[^\n]s",line);
printf("The number of words :: %d ",countWords(line));
}
To handle leading, trailing and extra spaces between two words the conditions inside the while is updated. In the above program two conditions such as:
the first condition if(line[i]!=' ' && line[i+1]==' ') this condition only increments the counts if a character is not as space and next character line[i+1] is contains a space. So, intermediate spaces are taken care using this condition. If there is two continous spaces then count is not incremented. This condition also handle the handle any leading spaces, by not incrementing the count when if line[i]==' '.
the second condition else if(line[i]!=' ' && line[i+1]=='\0') increment the counts only, if a null character is found. Menas the last word of a string.