String Exercises
Write a C program to count total number of alphabets, digits or special characters in a string using loop. How to find total number of alphabets, digits and special characters in a string in C programming.
Required knowledge
Basic C programming, C for loop, Array, Pointer, functions, Strings
Program to count number of alphabets, digits and special characters in string
/** * C program to count total number of alphabets, digits * and special characters in a string */ #include <stdio.h> #define MAX_SIZE 100 // Maximum string size int main() { char str[MAX_SIZE]; int alphabets, digits, others, i; alphabets = digits = others = i = 0; /* Input string from user */ printf("Enter any string : "); gets(str); /* * Check each character of string for alphabet, digit or special character */ while(str[i]!='\0') { if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z')) { alphabets++; } else if(str[i]>='0' && str[i]<='9') { digits++; } else { others++; } i++; } printf("Alphabets = %d\n", alphabets); printf("Digits = %d\n", digits); printf("Special characters = %d", others); return 0; }
You can also transform the program using pointers to get little geeky.
Program to count number of alphabets, digits and special characters in string using pointers
/** * C program to count total number of alphabets, digits * and special characters in a string using pointers */ #include <stdio.h> #define MAX_SIZE 100 // Maximum string size int main() { char str[MAX_SIZE]; char * s = str; int alphabets, digits, others; alphabets = digits = others = 0; /* Input string from user */ printf("Enter any string : "); gets(str); while(*s) { if((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z')) alphabets++; else if(*s>='0' && *s<='9') digits++; else others++; s++; } printf("Alphabets = %d\n", alphabets); printf("Digits = %d\n", digits); printf("Special characters = %d", others); return 0; }