C program to find total number of alphabets, digits or special characters in a string

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.

Example

Input

Input string: I love Codeforwin.

Output

Alphabets = 15
Digits = 0
Special characters = 3

Required knowledge

Basic C programming, Loop, String

Must know – Program to check input character is alphabet, digit or special character

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;
}

Output

Enter any string : Today is 12 November.
Alphabets = 15
Digits = 2
Special characters = 4

Happy coding 😉