题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
Point:The way to deal with this kind of problem is: from the back to the front!!!!
class Solution {
public:
void replaceSpace(char *str,int length) {
int len=strlen(str);
int sum=len,i,j;
for(i=0;i<len;i++){
if(str[i]==' ')sum+=2;
}
if(length<sum)return;
j=sum;
for(;i>=0;i--){
if(str[i]!=' ')
str[j--]=str[i];
else {
str[j--]='0';
str[j--]='2';
str[j--]='%';
}
}
}
};