C语言将字符串多个空格替换为单个空格时代码报错如何解决
C语言连续多空格替换为单空格问题解决方案
编译报错原因
两个报错均由main函数中delit的调用语法错误导致:
函数调用时不需要重复声明参数的类型,你写的delit(char *s, int i);是函数声明的写法,不是合法的调用语法,因此同时触发了「参数数量不足」和「char前缺少表达式」的报错。
- 临时修复方案:将该行代码修改为
delit(s, i);即可解决编译报错。
其他必须修复的逻辑与安全问题
仅修复调用语法后代码仍无法正常实现功能,还存在以下问题:
gets函数已被C标准正式移除,存在缓冲区溢出的高危安全漏洞,需替换为fgets读取输入。- 初始计算的字符串长度
l是固定值,删除字符后字符串长度会缩短,原有循环逻辑会出现越界访问,且会漏检多空格场景:例如3个连续空格删除第2个后,剩下的两个空格变为相邻,原有循环会跳过检测。 delit函数内每次删除后打印字符串属于调试逻辑,不需要保留。
完整修正代码
#include <stdio.h> #include <string.h> void delit(char *s, int i) { for (int j = i; s[j] != '\0'; j++) { s[j] = s[j + 1]; } } int main() { char s[100]; printf("输入长度小于100的字符串:"); fgets(s, sizeof(s), stdin); // 处理fgets读取的末尾换行符 int len = strlen(s); if (len > 0 && s[len - 1] == '\n') { s[len - 1] = '\0'; len--; } int i = 0; while (i < len - 1) { if (s[i] == ' ' && s[i + 1] == ' ') { delit(s, i + 1); len--; } else { i++; } } printf("处理后结果:%s\n", s); return 0; }
更高性能的优化实现(可选)
上述逐位移动字符的实现时间复杂度为O(n²),更推荐使用双指针法实现,无需移动字符,时间复杂度仅为O(n):
#include <stdio.h> #include <string.h> void replace_multi_space(char *s) { int read = 0, write = 0; while (s[read] != '\0') { if (s[read] == ' ') { // 只保留第一个空格 s[write++] = s[read++]; // 跳过后续所有连续空格 while (s[read] == ' ' && s[read] != '\0') read++; } else { s[write++] = s[read++]; } } s[write] = '\0'; } int main() { char s[100]; printf("输入长度小于100的字符串:"); fgets(s, sizeof(s), stdin); int len = strlen(s); if (len > 0 && s[len - 1] == '\n') s[len - 1] = '\0'; replace_multi_space(s); printf("处理后结果:%s\n", s); return 0; }
内容的提问来源于stack exchange,提问作者glorytothe12suns
相关产品推荐
相关产品推荐

