Question

I want to capitalize first letter of each word of an entered string.

This is what I've done (doesn't work yet)

void main() {
     char sentence[100];
     int i;

     printf("Enter your name and surnames: ");
     gets(sentence);

     for(i = 0; i<strlen(sentence); i++){
        if(sentence[i] == ' '){
            printf("%c", toupper(sentence[i]+1)); 
            //I want to advance to next item respect to space and capitalize it
            //But it doesn't work
        } else {
            printf("%c", sentence[i]);
        }
     }
} 

Input: james cameron

Wished Output: James Cameron

Was it helpful?

Solution

So close.

printf("%c", toupper(sentence[i]+1)); 

Should be

printf(" %c", toupper(sentence[i+1]));
i++;

Though you should probably check for the end of the string ('\0') too.

OTHER TIPS

Use strchr/strsep to search for word delimiters and then change the next character.

char *q, *p = sentence;
while (p) {
    q = strchr(p, ' ');
    if (!q) break;
    toupper(p[q - p + 1]);
    p = q;
}

An alternate approach: (create a function to capitalize)

1) Create an additional buffer of same length to contain modified results
2) Set first char of new string to upper case version of original string
3) Walk through the string searching for space.
4) Set next char of new string to upper case of char in original string

Code example:

void capitalize(char *str, char *new)
{
    int i=0;

    new[i] = toupper(str[0]);
    i++;//increment after every look
    while(str[i] != '\0')
    {
        if(isspace(str[i])) 
        {
            new[i] = str[i];
            new[i+1] = toupper(str[i+1]);
            i+=2;//look twice, increment twice
        }
        else
        {
            new[i] = str[i];        
            i++;//increment after every look
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top