去除字符串中的空格 C语言实现 一般写法
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
int main(void)
{
char *from = " 1 2 4 5 6 ";//测试数据
char to[20]; //保存数据
int i = 0; //临时变量
int j = 0; /临时变量
int len = strlen(from); //获取字符串的长度
while (len>0) //进行循环
{
if (from[i] != ' ') //判断是否为空格
{
*(to + j) = from[i]; //拷贝数据
j++;
}
i++;
len--;
}
*(to + j) = '\0'; //添加结尾
printf("%s", to);
return 0;
}
函数封装
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
int delete_spance(char *source, char *new_str)
{
char *from = source;
char *to = new_str;
int i = 0; //临时变量
int j = 0; //临时变量
int len = strlen(from); //获取字符串的长度
while (len > 0) //进行循环
{
if (from[i] != ' ') //判断是否为空格
{
*(to + j) = from[i]; //拷贝数据
j++;
}
i++;
len--;
}
*(to + j) = '\0'; //添加结尾
return 0;
}
int main(void)
{
char *from = " 1 2 4 5 6 ";//测试数据
char to[20]; //保存数据
delete_spance(from, to);
printf("%s", to);
return 0;
}
本文介绍了一种使用C语言去除字符串中空格的方法。通过两个示例展示了基本的实现思路:一是直接操作字符串,二是将功能封装为独立函数。这两种方法均遍历输入字符串,忽略空格并将有效字符复制到新位置。

被折叠的 条评论
为什么被折叠?



