您的位置:首页 > 职场人生

剑指offer面试题4—替换空格

2015-01-09 15:34 483 查看
题目比较简单,把字符串中的空格替换为相应的字符串

如果从前开始循环替换,每移动一个元素,后面的数据都需要移动,因此选用的方法应该是从后面行前替换

#include "static.h"
#include <iostream>
using namespace std;

void ReplaceBlank(char *Src, char *transString,int Length)
{
	int transSize = 0;
	int srcSize = 0;
	int dstSize = 0;
	int tabSize = 0;
	while (transString[transSize] != '\0')
	{
		transSize++;
	}
	while (Src[srcSize] != '\0')
	{
		if (Src[srcSize] == ' ')
		{
			tabSize++;
		}
		srcSize++;//<表示原始字符串的长度
	}
	dstSize = srcSize+(transSize-1)*tabSize;
	if (dstSize > Length)
	{
		cout<<"the arry's memery is not enough";
		return;
	}
	while (srcSize>= 0 && dstSize > srcSize)
	{
		if (Src[srcSize] == ' ')
		{
			memcpy(Src+(dstSize-transSize+1),transString,transSize);
			dstSize -= transSize;
			srcSize--;
		}
		else
		{
			Src[dstSize--] = Src[srcSize--];
		}
	}
}

int main()
{   
	const int Length = 50;
	char src[Length];
	char* transString = "%20";
	cout << "Please enter the origin string"<<endl;
	cin.getline(src,50);
	printf("%s \n",src);
	ReplaceBlank(src,transString,Length);
	printf("%s \n",src);
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: