【问题标题】:Simple capitalization of first letter of each word in C [duplicate]C中每个单词的第一个字母的简单大写[重复]
【发布时间】:2013-11-18 00:55:14
【问题描述】:

我想将输入字符串的每个单词的首字母大写。

这就是我所做的(还没有工作)

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

希望输出:詹姆斯·卡梅隆

【问题讨论】:

  • gets() 的使用风格极差。无法安全使用,已在最新版C标准中删除。
  • 有趣的是,3小时前也有人问过同样的问题:stackoverflow.com/questions/20036553/…
  • 另外:包括相关的头文件#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt;,如果你不做坏事可能会发生
  • @MitchWheat - inspace() 你的意思是isspace()

标签: c capitalization


【解决方案1】:

如此接近。

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

应该是

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

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

【讨论】:

  • 输出为:James Ccameron
  • 你添加了i++吗?
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    代码示例:

    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
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-06
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多