Write A Program To Count The Number of Words
Write A Program To Count The Number of Words
text
Program finding number of words, blank spaces, special symbols, digits, vowels using
pointers
1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<conio.h>
/*low implies that position of pointer is within a word*/
#define low 1
/*high implies that position of pointer is out of word.*/
#define high 0
void main() {
int nob, now, nod, nov, nos, pos = high;
char *str;
nob = now = nod = nov = nos = 0;
clrscr();
printf("Enter any string : ");
gets(str);
while (*str != '\0') {
if (*str == ' ') {
// counting number of blank spaces.
pos = high;
++nob;
} else if (pos == high) {
// counting number of words.
pos = low;
++now;
}
if (isdigit(*str)) /* counting number of digits. */
++nod;
if (isalpha(*str)) /* counting number of vowels */
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3 }
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
switch (*str) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
++nov;
break;
}
/* counting number of special characters */
if (!isdigit(*str) && !isalpha(*str))
++nos;
str++;
}
printf("\nNumber
printf("\nNumber
printf("\nNumber
printf("\nNumber
printf("\nNumber
getch();
of
of
of
of
of
3
5
4
5
5
5
6
5
7
5
8
5
9
6
0
6
1
6
2
6
3
6
4
Output :
Explanation of Program :
Now we are going to accept string using gets(). We are not using scanf() to accept string
because scanf() will accept string only upto whitespace.
2 gets(str);
We are accepting string using character pointer. Now we are checking each character
using character pointer and in each loop we are incrementing the character pointer.
1 if
2
3
4}
5
6
7}
In the if block we are checking that whether our pointer position is within the word or
outside the word.
#include <stdlib.h>
#include <stdio.h>
int countWords(FILE *f){
int count = 0;
char ch;
while ((ch = fgetc(f)) != EOF){
if (ch == '\n')
count++;
}
return count;
}
int main(void){
int wordCount = 0;
FILE *rFile = fopen("american0.txt", "r");
wordCount += countWords(rFile);
printf("%d", wordCount);
return 0;