C首字母大写忽略第一个单词

Chr*_*sMe -2 c string whitespace toupper

我试图使每个第一个单词字母大写,但它忽略了第一个单词并跳到第二个单词."apple macbook"应该是"Apple Macbook",但它给了我"苹果Macbook".如果我printf(" %c", toupper(string[0]));在for循环之前添加并在for循环中更改p=1它会给我正确的结果,但如果string以空格开头则会失败.这是代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

niy*_*asc 5

一个简单的解决方法可以如下:

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

  • @xxxvodnikxxx:C的短路评估保证当左表达式为真时,不计算逻辑或"||"的表达式权,这意味着整个表达式必须为真. (2认同)