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)
一个简单的解决方法可以如下:
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)