问题描述:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
代码:
classSolution {
public:
voidreplaceSpace(char*str,intlength) {
char* temp = newchar[length+1];
inttmp=0;
for(inti=0;i<length;i++)
{
if(*(str+i)!=' ')
{
temp[tmp]=*(str+i);
tmp++;
}
else
{
temp[tmp]='%';
temp[tmp+1]='2';
temp[tmp+2]='0';
tmp=tmp+3;
}
}
for(inti=0;i<tmp;i++)
{
str[i]=temp[i];
}
if(temp)
{
delete temp;
temp=NULL;
}
}
};