Count Alphabets Digits and Symbols in a String

Code

#include <stdio.h>
#include <stdint.h>

void classify_chars(const char *str, uint8_t *alpha, uint8_t *digit, uint8_t *symbol) {
    int index = 0;
    *alpha = 0;
    *digit = 0;
    *symbol = 0;
    while (str[index] != '\0') {
        if ((str[index] >= 'A' && str[index] <= 'Z') || 
            (str[index] >= 'a' && str[index] <= 'z')) {
            // current char is alpha
            (*alpha)++;
        } else if (str[index] >= '0' && str[index] <= '9') {
            // current char is digit
            (*digit)++;
        } else if (str[index] != ' ') {
            // current char is something else
            (*symbol)++;
        }
        index++;
    }
}

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove newline
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    uint8_t alpha = 0, digit = 0, symbol = 0;
    classify_chars(str, &alpha, &digit, &symbol);
    printf("Alphabets = %u\nDigits = %u\nSymbols = %u", alpha, digit, symbol);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

C99_Firmware!

Expected Output

Alphabets = 9 Digits = 2 Symbols = 2