-2

我试图使每个第一个单词的字母大写,但它忽略了第一个单词并跳到第二个。“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;
}
4

2 回答 2

5

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

 for(p = 0; p<strlen(string); p++)
    {
        if(p == 0 || string[p - 1] == ' ')
        {
            printf("%c", toupper(string[p]));
        }
        else
        {
            printf("%c", string[p]);
        }
    }
于 2015-11-30T12:36:06.767 回答
0

改变这个:

char string[] = "apple macbook";

对此:

char string[] = " apple macbook";

你会得到你想要的。

原因是在你的循环中,你会搜索一个空格来更改之后的字母。


但是,niyasc 的答案更好,因为它不会更改输入字符串,而是更改程序的逻辑。

我这样做主要是为了利用你遇到的行为的原因,所以你被敦促自己改变你的逻辑。:)

于 2015-11-30T12:36:11.957 回答