C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Count digits, spaces, special chars

C Program: Count Digits, Spaces, and Special Characters in a String

C

#include <stdio.h>

 

int main() {

    char str[200];

    int i, digits = 0, spaces = 0, special = 0;

 

    // Input string safely

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin);  // safer input

 

    // Traverse string

    for (i = 0; str[i] != '\0'; i++) {

        if (str[i] >= '0' && str[i] <= '9')

            digits++;

        else if (str[i] == ' ')

            spaces++;

        else if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))

            continue; // skip letters

        else if (str[i] != '\n') // exclude newline from special chars

            special++;

    }

 

    // Display results

    printf("Number of digits: %d\n", digits);

    printf("Number of spaces: %d\n", spaces);

    printf("Number of special characters: %d\n", special);

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter a string: Hello 123! Welcome@IT
Number of digits: 3
Number of spaces: 2
Number of special characters: 2

Explanation

  • The program scans each character in the string.
  • It counts:
    • Digits → '0' to '9'
    • Spaces → ' '
    • Special characters → Any non-alphabet, non-digit, non-space character
  • The newline ('\n') from fgets() is ignored.