简单大写C中每个单词的首字母

时间:2013-11-18 00:55:14

标签: c capitalization

我想大写输入字符串中每个单词的第一个字母。

这就是我所做的(暂时还没有)

void main() {
     char sentence[100];
     int i;

     printf("Enter your name and surnames: ");
     gets(sentence);

     for(i = 0; i<strlen(sentence); i++){
        if(sentence[i] == ' '){
            printf("%c", toupper(sentence[i]+1)); 
            //I want to advance to next item respect to space and capitalize it
            //But it doesn't work
        } else {
            printf("%c", sentence[i]);
        }
     }
} 

输入:james cameron

希望输出:詹姆斯卡梅隆

3 个答案:

答案 0 :(得分:1)

如此接近。

printf("%c", toupper(sentence[i]+1)); 

应该是

printf(" %c", toupper(sentence[i+1]));
i++;

虽然您应该检查字符串的结尾('\0')。

答案 1 :(得分:1)

使用strchr / strsep搜索字词分隔符,然后更改下一个字符。

char *q, *p = sentence;
while (p) {
    q = strchr(p, ' ');
    if (!q) break;
    toupper(p[q - p + 1]);
    p = q;
}

答案 2 :(得分:0)

替代方法:(创建一个大写的函数)

1) 创建一个相同长度的附加缓冲区以包含修改后的结果
2) 将新字符串的第一个字符串设置为原始字符串的大写版本
3) 浏览字符串以搜索空格 4) 在原始字符串中将新字符串的下一个字符串设置为char的大写

代码示例:

void capitalize(char *str, char *new)
{
    int i=0;

    new[i] = toupper(str[0]);
    i++;//increment after every look
    while(str[i] != '\0')
    {
        if(isspace(str[i])) 
        {
            new[i] = str[i];
            new[i+1] = toupper(str[i+1]);
            i+=2;//look twice, increment twice
        }
        else
        {
            new[i] = str[i];        
            i++;//increment after every look
        }
    }
}
相关问题