//剑指offer 面试题4---替换空格
//题目:请实现一个函数,把字符串中的每个空格替换成“%20”;例如输入“ we are happy”,则输出“we%20are%20happy”.
//题目:请实现一个函数,把字符串中的每个空格替换成“%20”;例如输入“ we are happy”,则输出“we%20are%20happy”.
//自己编写
#include <iostream>
#include <string>
using namespace std;
void ReplaceSpace(const char *pInput,long lLength,char *pOutput)
{
int i;
char *temp=pOutput;
for(i=0;i<lLength;i++)
{
if(pInput[i]!=' ')
*pOutput++=pInput[i];
else
{
*pOutput++='%';
*pOutput++='2';
*pOutput++='0';
}
}
*pOutput=NULL;
pOutput=temp;
}
int main()
{
const int Size=10000;
long str;
char pIn[Size];
cin.getline(pIn,Size);
char *pOu=new char[Size];
str=strlen(pIn);
cout<<str<<endl;
ReplaceSpace(pIn,str,pOu);
cout<<pOu<<endl;
delete [] pOu;
return 0;
}
测试结果
输入11个空格测试