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

C语言如何提取字符串首字符及空格后字符拼接为新字符串

问题排查

  • 你声明的result是单字符类型,只能存储1个字符,无法容纳拼接后的多字符结果,需要修改为足够长度的字符数组存储新字符串
  • 现有逻辑仅提取了空格后的首个字符,漏掉了原字符串的首字符
  • C语言不支持直接用+=给字符串拼接单个字符,strcat的作用是拼接两个完整的C风格字符串,你这种逐个字符追加的场景,直接维护结果数组的写入下标实现更简单

修正后代码

#include <stdio.h>
#include <string.h>

int main()
{
    char string[] = "hello world wide";
    int stringLength = strlen(string);
    int i;
    // 结果数组长度按照最坏情况预留,额外+1用于存储字符串结束符'\0'
    char result[256] = {0};
    int write_pos = 0;

    // 先写入原字符串首字符
    result[write_pos++] = string[0];

    for (i = 0; i < stringLength; i++)
    {
        // 加边界判断避免空格在字符串末尾时触发数组越界
        if (string[i] == ' ' && i < stringLength - 1)
        {
            printf("Found space at the index: %d\n", i);
            printf("Next char: %c\n", string[i+1]);
            // 写入空格后的首个字符,写入位置后移
            result[write_pos++] = string[i + 1];
        }
    }
    // 末尾补结束符,构成合法C字符串
    result[write_pos] = '\0';

    printf("\n拼接后的新字符串:%s\n", result);
    return 0;
}

补充说明

如果一定要用strcat实现拼接,需要先把要追加的单个字符封装成长度为2的临时字符串(字符+结束符),再调用strcat(result, 临时字符串),相比直接操作数组下标效率更低,没有必要用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:54:01