Search code examples
cstringwhitespacetoupper

C first letter to uppercase ignores first word


I am trying to make every first word letter capital, but it ignores the first word and jumps to second. "apple macbook" should be "Apple Macbook", but it gives me "apple Macbook". If I add printf(" %c", toupper(string[0])); before for loop and change p=1 in for loop it gives me correct result, but if string starts with a space then it will fail. Here is the code:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
    char string[] = "apple macbook";
    int p;
    for(p = 0; p<strlen(string); p++)
    {
        if(string[p] == ' ')
        {
            printf(" %c", toupper(string[p+1]));
            p++;
        }
        else
        {
            printf("%c", string[p]);
        }
    }
    return 0;
}

Solution

  • A simple work around can be as follows:

     for(p = 0; p<strlen(string); p++)
        {
            if(p == 0 || string[p - 1] == ' ')
            {
                printf("%c", toupper(string[p]));
            }
            else
            {
                printf("%c", string[p]);
            }
        }