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:

       char stringa[] = "some string here";  // sizeof stringa == 17
    

    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;
    }