You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言中不使用数组将每个单词首字母从小写转为大写?

实现每个单词首字母大写的修改方案

要实现仅每个单词首字母大写的需求,核心是判断当前字符是否是单词的开头——也就是前一个字符是否为非字母(比如空格、换行符)。我们可以新增一个变量跟踪前一个字符是否为字母,结合ASCII码完成转换逻辑,不需要数组或额外函数。

修改后的代码如下:

#include <stdio.h>
int main() 
{
    FILE *input;
    FILE *output;

    input  = fopen ("poem.txt", "r");
    output = fopen ("poem_modified.txt", "w");

    if (input == NULL || output == NULL)
    {
        printf("Problem! \n");
        return 1;
    }
    int ch;
    // 标记前一个字符是否为字母,初始为0(开头的字符若为字母则是单词首字母)
    int prev_is_letter = 0;

    while((ch=getc(input)) != EOF)
    {
        if (ch >= 'a' && ch <= 'z')
        {
            // 如果前一个不是字母,说明是单词首字母,转大写
            if (!prev_is_letter)
            {
                ch -= 32;
            }
            prev_is_letter = 1;
        }
        else if (ch >= 'A' && ch <= 'Z')
        {
            // 如果前一个是字母,说明是单词中间的大写,转小写
            if (prev_is_letter)
            {
                ch += 32;
            }
            prev_is_letter = 1;
        }
        else
        {
            // 非字母字符直接输出,标记前一个不是字母
            prev_is_letter = 0;
        }
        fprintf(output, "%c", ch);
    }

    fclose(input);
    fclose(output); 
    return 0;
}

处理后poem_modified.txt的内容为:

The House Cat Sits

And Smiles And Sings

He Knows A Lot

Of Secret Things

内容的提问来源于stack exchange,提问作者Rosaline

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:40:33