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 string: I love programming.
Output: Alphabets = 16
Digits = 0
Special character = 3
Total length = 19

Required knowledge

Basic C programming, Loop, String

It would be really easy to code solution of this program if you already know how to check whether a character is alphabets, digits or special character. As logic to this program is similar to mentioned program. What we need to do in extra is run a loop from 0 to end of the string.

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 size of the string


int main()
{
    char string[MAX_SIZE];
    int alphabets, digits, others, i;

    alphabets = digits = others = i = 0;


    /* Reads a string from user */
    printf("Enter any string : ");
    gets(string);

    /*
     * Checks each character of string
     */
    while(string[i]!='\0')
    {
        if((string[i]>='a' && string[i]<='z') || (string[i]>='A' && string[i]<='Z'))
        {
            alphabets++;
        }
        else if(string[i]>='0' && string[i]<='9')
        {
            digits++;
        }
        else
        {
            others++;
        }

        i++;
    }

    printf("Alphabets = %d\n", alphabets);
    printf("Digits = %d\n", digits);
    printf("Special characters = %d\n", others);

    return 0;
}


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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment