Search code examples
csplitc-stringsfunction-definitiontoupper

Capitalize first letter of a word in a string in C


I have to capitalize the first letter of every word (words are separated by a space) into a given array of char. I wrote the code but I can't figure out why it's not working nor displaying anything in output.

Here's the code:

void LetterCapitalize(char *str) {
    char *str2;
    int i = 0;
    str2[i] = toupper(str[0]);
    i++;
    while (str[i]) {
        if (str[i] == ' ') {
            str2[i] = str[i];
            str2[i + 1] = toupper(str[i] + 1);
            i += 2;
        } else {
            str2[i] = str[i];
            i++;
        }
    }
    printf ("%s", str2);
}

And here's the main:

int main(void) {
    char stringa[16] = "some string here";
    LetterCapitalize(stringa);
    return 0;
}

Solution

  • There are multiple problems:

    • The string defined in main is not null terminated because the initializer has exactly 16 characters, the defined length of the array, so there is no space for the null terminator. It is safer to omit the array length and let the compiler compute it from the initializer, including the null terminator:
       char stringa[] = "some string here";  // sizeof stringa == 17
    
    • str2 is uninitialized: storing characters to it has undefined behavior. You could instead either modify the argument string in place or allocate a copy and modify that.

    • the logic in LetterCapitalize is risky: you assume that words are separated by a single space and that the string does not end with a space.

    • the char argument to toupper() should be cast as (unsigned char) to avoid undefined behavior on negative char values on platforms where the type char is signed by default.

    Here is a modified version:

    #include <ctype.h>
    #include <stdio.h>
    
    char *LetterCapitalize(char *str) {
        unsigned char c, last = ' ';
        // uppercase characters that follow a space or at the start of the string
        for (size_t i = 0; (c = str[i]) != '\0'; last = c, i++) {
            if (last == ' ')
                str[i] = toupper(c);
        }
        return str;
    }
    
    int main() {
        char stringa[] = "some string here";
        puts(LetterCapitalize(stringa));
        return 0;
    }