xqn2017

导航

【剑指offer】将字符串中的空格替换成"%20"

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

char *ReplaceSpace(char *str,int MaxLen)
{
	int SpaceNum = 0;
	int srcIdx = 0;
	int srcLen = 0;
	int dstIdx = 0;
	int dstLen = 0;
	char *strTmp = str;
	if(NULL == str)
	{
		return NULL;
	}
	while('\0' != *strTmp)
	{
		srcLen++;
		if(' ' == *strTmp)
		{
			SpaceNum++;
		}
		strTmp++;
	}
	dstLen = srcLen + 2*SpaceNum;
	if(dstLen > MaxLen)
	{
		cout<<"error !! dstLen is more than MaxLen!";
		return NULL;
	}
	while(srcLen >=0 &&dstLen > srcLen)
	{
		if(' ' == str[srcLen] )
		{
			str[dstLen--] = '0'; 
			str[dstLen--] = '2'; 
			str[dstLen--] = '%'; 
		}
		else
		{
			str[dstLen--] = str[srcLen];
			//cout<<str[srcLen]<<endl;
		}
		srcLen--;
	}
	return str;
}
int main(void)  
{  
	char str[30] = "you are a coder!";
	char *resultStr = NULL;
	resultStr = ReplaceSpace(str,30);
	if(resultStr != NULL)
	{
		while(*resultStr != '\0')
		{
			cout<<*resultStr;
			resultStr++;
			
		}
	}
	else
	{
		cout<<"Result is NULL";
	}
	cout<<endl;
	
	return 0;  
}    

  

posted on 2017-12-11 18:20  xqn2017  阅读(158)  评论(0编辑  收藏  举报