20170928_替换空格

20170928_替换空格


//面试题4
//实现一个函数,将字符串中的每个空格都转换成"%20"。
//例如:"we are happy."
//转换之后是:"we20%are20%happy."

//直观思路:从前至后,依次扫描字符串中的每个字符,遇到空格时就将其替换为"20%",直到字符串结尾标识符'\0'。
//时间复杂度是:O(n平方)
//进阶思路:从后至前,使用两个指针,依次扫描字符串中的每个字符,遇到空格时就将其替换为"20%",直到两个指针相等。
//时间复杂度是:O(n)

#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;

class Solutions
{
public:
	void ReplaceBlank(char str[], int length)	//length:代表字符数组的总长度
	{
		if(str==nullptr || length<=0)	//输入的字符串是空,或者字符串长度是0
			return;
		int OriginalLen=0;
		int NumOfBlank=0;
		int i=0;
		while(str[i] != '\0')
		{
			++OriginalLen;
			if(str[i] == ' ')
				++NumOfBlank;
			++i;
		}
		int NewLen=0;
		NewLen=OriginalLen+NumOfBlank*2;
		if(NewLen>length)	//字符数组溢出
			return;
		//cout<<OriginalLen<<","<<NumOfBlank<<","<<NewLen<<endl;
		//设置两个指针
		int p1=OriginalLen;	//指向旧数组的末尾
		int p2=NewLen;	//指向新数组的末尾
		while(p2 != p1)
		{
			if(str[p1] == ' ')
			{
				str[p2--]='0';
				str[p2--]='2';
				str[p2--]='%';
				--p1;
			}
			else
			{
				str[p2]=str[p1];
				--p1;
				--p2;
			}
		}
	}
};

int main(void)
{
	const int SIZE=50;
	char str[SIZE]="we are  happy.";
	//char str[SIZE]=" wearehappy.";
	//char str[SIZE]="wearehappy. ";
	//char str[SIZE]="wearehappy.";
	//char str[SIZE]="";
	cout<<str<<endl;
	Solutions object;
	object.ReplaceBlank(str,SIZE);
	cout<<str<<endl;

	system("pause");
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值