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

C语言不使用预定义函数去除字符串多余空格的问题及优化

去除C语言字符串多余空格:解决末尾空格问题+更优实现

你的代码运行后xyz后面多了个空格,问题出在处理末尾前的空格时:当遍历到xyz后的第一个空格,此时它不是字符串最后一位,你的逻辑会输出这个空格;后续的末尾空格虽然被跳过,但已经输出的空格没法撤回,就导致了末尾多余空格。

快速修复原代码

可以调整逻辑,先跳过开头所有空格,然后遇到空格时,只在后面还有有效字符的情况下才输出,同时跳过连续空格:

#include <stdio.h>

int main() {
    char str[30] = "   abcdef   abc   xyz   ";
    int i = 0;
    printf("(");
    // 跳过开头所有空格
    while (str[i] == ' ') {
        i++;
    }
    while (str[i] != '\0') {
        if (str[i] != ' ') {
            printf("%c", str[i]);
            i++;
        } else {
            // 只有后面还有非空格字符时才输出空格
            printf(" ");
            i++;
            // 跳过后续连续空格
            while (str[i] == ' ') {
                i++;
            }
        }
    }
    printf(")\n");
    return 0;
}

运行后就能得到你要的(abcdef abc xyz)。

更优实现(不依赖任何预定义函数)

如果严格要求不能用strlen这类预定义函数,推荐用双指针法原地修改字符串,逻辑更清晰,也更高效:

#include <stdio.h>

void trimExtraSpaces(char *str) {
    int read_ptr = 0, write_ptr = 0;
    // 跳过开头所有空格
    while (str[read_ptr] == ' ') {
        read_ptr++;
    }
    // 遍历处理字符串
    while (str[read_ptr] != '\0') {
        if (str[read_ptr] != ' ') {
            str[write_ptr++] = str[read_ptr++];
        } else {
            // 写入一个空格,然后跳过所有连续空格
            str[write_ptr++] = ' ';
            read_ptr++;
            while (str[read_ptr] == ' ') {
                read_ptr++;
            }
        }
    }
    // 处理最后可能多写的空格
    if (write_ptr > 0 && str[write_ptr - 1] == ' ') {
        write_ptr--;
    }
    // 添加字符串结束符
    str[write_ptr] = '\0';
}

int main() {
    char str[30] = "   abcdef   abc   xyz   ";
    trimExtraSpaces(str);
    printf("(%s)\n", str);
    return 0;
}

这个方案的好处:

  • 完全不依赖任何预定义字符串函数,纯手动处理
  • 原地修改字符串,不需要额外内存
  • 逻辑闭环:处理开头空格、中间连续空格、末尾多余空格,一步到位

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:32:40