【发布时间】:2015-11-30 12:31:14
【问题描述】:
我试图使每个第一个单词的字母大写,但它忽略了第一个单词并跳到第二个。
“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;
}
【问题讨论】:
-
显然代码不起作用,因为字符串中的第一个字母是特殊情况,前面没有空格。您必须单独处理这种特殊情况。另外,你需要从0迭代到
strlen(string)-1,否则你的程序总是会破坏空终止符,然后当空格是字符串的最后一个字母时崩溃。 -
你感到惊讶吗? “Apple”之前没有空格。
-
您在 if 语句中测试空格字符。下一个字符将转换为大写。试试
if (p==0 || string[p] == ' ')
标签: c string whitespace toupper