How to check if a word is all uppercase or all lowercase or capitalized in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>

// Checks if the word is all uppercase, all lowercase, or capitalized
bool verifyAllUpperORAllLowerORIsCapitalized(const char *word) {
    int upper = 0;
    int lower = 0;
    size_t len = strlen(word);

    for (size_t i = 0; i < len; i++) {
        if (islower((unsigned char)word[i])) {
            lower++;
        } else if (isupper((unsigned char)word[i])) {
            upper++;
        }
    }

    if (upper == 0) return true; // all lowercase
    if (lower == 0) return true; // all uppercase
    if (upper == 1 && isupper((unsigned char)word[0])) return true; // capitalized

    return false;
}

// Runs a test case and prints result
void runTest(const char *word) {
    printf("Testing word: \"%s\"\n", word);

    if (verifyAllUpperORAllLowerORIsCapitalized(word)) {
        printf("OK\n");
    } else {
        printf("Error\n");
    }
}

int main() {
    runTest("PROGRAMMING");   
    runTest("programming");   
    runTest("Programming");   
    runTest("ProGramMing");   
    
    return 0;
}


/*
run:

Testing word: "PROGRAMMING"
OK

Testing word: "programming"
OK

Testing word: "Programming"
OK

Testing word: "ProGramMing"
Error

*/


 



answered Oct 26, 2025 by avibootz
edited Oct 27, 2025 by avibootz
...