我试图使每个第一个单词的字母大写,但它忽略了第一个单词并跳到第二个。“apple macbook”应该是“Apple Macbook”,但它给了我“apple Macbook”。如果我在 for 循环之前添加并在printf(" %c", toupper(string[0]));
for 循环中进行更改p=1
,它会给我正确的结果,但如果字符串以空格开头,那么它将失败。这是代码:
#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;
}