×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to count digits, spaces, special characters, alphabets in a string

In this C program, we are going to learn how to count digits, spaces, special characters and alphabets?.

Problem statement

Given a string and we have to count digits, spaces, special characters and alphabets using C program.

C program to count digits, spaces, special characters, alphabets in a string

/*C program to count digits, spaces, special characters, 
alphabets in a string.*/

#include <stdio.h>

int main()
{
    char str[100];
    int countDigits, countAlphabet, countSpecialChar, countSpaces;
    int counter;

    //assign all counters to zero
    countDigits = countAlphabet = countSpecialChar = countSpaces = 0;

    printf("Enter a string: ");
    gets(str);

    for (counter = 0; str[counter] != NULL; counter++) {

        if (str[counter] >= '0' && str[counter] <= '9')
            countDigits++;
        else if ((str[counter] >= 'A' && str[counter] <= 'Z') || (str[counter] >= 'a' && str[counter] <= 'z'))
            countAlphabet++;
        else if (str[counter] == ' ')
            countSpaces++;
        else
            countSpecialChar++;
    }

    printf("\nDigits: %d \nAlphabets: %d \nSpaces: %d \nSpecial Characters: %d", countDigits, countAlphabet, countSpaces, countSpecialChar);

    return 0;
}

Output

Enter a string: This is test string, 123 @#% 98.

Digits: 5
Alphabets: 16
Spaces: 6
Special Characters: 5

C Strings User-defined Functions Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.