1. 程式人生 > >劍指offer面試題4—替換空格

劍指offer面試題4—替換空格

題目比較簡單,把字串中的空格替換為相應的字串

如果從前開始迴圈替換,每移動一個元素,後面的資料都需要移動,因此選用的方法應該是從後面行前替換

#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;
}