去掉字符串中的所有空格

       要去掉字符串中所有的空格,思路很自然:碰到一个空格,将其删掉,然后后面的字符前移,但当空字符比较多的时候,总这么移动,难道不复杂么?还是想想另外的办法吧。

      上面的方法时间复杂度比较高,下面,我们用空间来换时间:

 

#include <iostream>
using namespace std;

void deleteAllSpace(char str[])
{
	int len = strlen(str);
	char *p = new char[len + 1];
	int i, j = 0;
	for(i = 0; i < len; i++)
	{
		if(' ' != str[i])
		{
			p[j++] = str[i];
		}
	}

	p[j] = '\0';
	strcpy(str, p);
}

int main()
{
	char str1[] = "abc";
	char str2[] = "  abc";
	char str3[] = "abc ";
	char str4[] = " a b c ";
	char str5[] = " a  b  c ";
	char str6[] = " a  bcd  e ";

	deleteAllSpace(str1);
	deleteAllSpace(str2);
	deleteAllSpace(str3);
	deleteAllSpace(str4);
	deleteAllSpace(str5);
	deleteAllSpace(str6);

	printf("%s\n", str1);
	printf("%s\n", str2);	
	printf("%s\n", str3);
	printf("%s\n", str4);
	printf("%s\n", str5);
	printf("%s\n", str6);

	return 0;
}

 

     上面这个思路不错,但是,main中的程序太丑陋了,改为如下:

 

 

#include <iostream>
using namespace std;

void deleteAllSpace(char str[])
{
	int len = strlen(str);
	char *p = new char[len + 1];
	int i, j = 0;
	for(i = 0; i < len; i++)
	{
		if(' ' != str[i])
		{
			p[j++] = str[i];
		}
	}

	p[j] = '\0';
	strcpy(str, p);
	delete []p;

}

int main()
{
	char str[6][20] =
	{
		"abc",
		"  abc",
		"abc ",
		" a b c ",
		" a  b  c ",
		" a  bcd  e "
	};

	int i;
	for(i = 0; i < 6; i++)
	{
		deleteAllSpace(str[i]);
		printf("%s\n", str[i]);

	}

	return 0;
}

 

       事实上,上述程序的空间复杂度较高,那有没有更好的办法呢?有,如下:

 

#include <iostream>
using namespace std;

void deleteAllSpace(char str[])
{
	char *p = str;
	int k = 0;

	while('\0' != *p)
	{
		if(' ' != *p)
		{
			str[k++] = *p++; 
		}
		else
		{
			p++;
		}
	}
	
	str[k] = '\0';
}

int main()
{
	char str[6][20] =
	{
		"abc",
		"  abc",
		"abc ",
		" a b c ",
		" a  b  c ",
		" a  bcd  e "
	};

	int i;
	for(i = 0; i < 6; i++)
	{
		deleteAllSpace(str[i]);
		printf("%s\n", str[i]);

	}

	return 0;
}
 

        OK.
 

 

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值