C Program to Count number of words,digits,vowels using pointers
Write a program to count the number of words, lines and characters in a text
Program finding number of words, blank spaces, special symbols, digits, vowels using pointers
Count Number of Words using Pointer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | #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 */ 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 of words %d", now); printf("\nNumber of spaces %d", nob); printf("\nNumber of vowels %d", nov); printf("\nNumber of digits %d", nod); printf("\nNumber of special characters %d", nos); getch(); } |
Output :
1 2 3 4 5 6 7 | Enter any string : pritesh a taral from c4learn.com Number of words 5 Number of spaces 4 Number of vowels 9 Number of digits 1 Number of special characters 5 |
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.
1 2 | printf("Enter any string:"); 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 2 3 4 | while (*str != '\0') { ------- ------- } |
Whenever first space is encountered then number of space counter is incremented by one.
1 2 3 4 5 6 7 | if (*str == ' ') { pos = high; // counting number of blank spaces. ++nob; } else if (pos == high) { pos = low; // counting number of words. ++now; } |
In the if block we are checking that whether our pointer position is within the word or outside the word.