C语言---去掉字符串中的空格

发布时间 2023-10-18 14:15:08作者: 皓然123

有时候,我们会遇到,字符串中有空格,那如何删除呢?

要删除空格,就需要找到空格,找到空格,就需要遍历字符串。

下面是示例代码:(分别使用了for 和while 循环)

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

void fun(char *str)
{
	int i=0;
	char *p;
	/*标记:p=str表示指针指向字符串首地址做标记*/

	for(p=str;*p!='\0';p++)
		/*遍历:不等于'\0'表示只要字符串不结束,就一直p++。*/
		if(*p!=' ')
			str[i++]=*p;
	/*删除:如果字符串不等于空格,即有内容就存入字符串。等于空格就不储存,但是指针还是p++继续后移,跳过储存空格相当于删除。*/
	str[i]='\0';
}

void fun1(char *str)
{
	int i=0;
	char *p=str;
	while(*p)
	{
		if(*p!=' ')
			str[i++]=*p;
		p++;
	}
	/*除了for循环遍历,也可while循环遍历。注意 p++在if语句后,不然会漏掉第一个字符。*/
	str[i]='\0';
}

void main()
{
	char str[100];
	int n;

	printf("input a string:");
	gets(str);
	puts(str);
	printf("str old :%s\n",str);

	/*输入输出原字符串*/
	fun(str);
	/*利用fun函数删除空格*/
	printf("str new :%s\n",str);
}

 

结果:

input a string:aaa bbb  ccc  dddd111
aaa bbb  ccc  dddd111
str old :aaa bbb  ccc  dddd111
str new :aaabbbcccdddd111