OneBite.Dev - Coding blog in a bite size

capitalize a string in C

Code snippet on how to capitalize a string in C

  char* upper(char s[]) {
    int i = 0;
    while (s[i] != '\0') {
        if (s[i] >= 'a' && s[i] <= 'z') {
            s[i] = s[i] - 32;
        }
        i++;
    }
    return s;
}

This code takes a string as an input, loops through it character by character, and converts any lowercase letter to uppercase by subtracting 32 from its ASCII value. The loop is terminated when the null character (\0) is encountered. This indicates that the string has ended. Finally the capitalized string is returned as a pointer to its first character.

c