请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
具体思路为,从左到右查找空格个数,从右到左进行插入操作。
class Solution {
public:
void replaceSpace(char *str,int length) {
if (str==NULL||length<=0)
return;
int oldLength=0;
int numberOfBlank=0;
int newLength=0;
while(str[oldLength]!='\0'){
if (str[oldLength]==' ')
++numberOfBlank;
++oldLength;
}
newLength=oldLength+2*numberOfBlank;
int pointToOldLength=oldLength;
int pointToNewLength=newLength;
if(newLength>length)
return;
while(pointToOldLength>=0&&pointToNewLength>pointToOldLength){
if(str[pointToOldLength]==' '){
str[pointToNewLength--]='0';
str[pointToNewLength--]='2';
str[pointToNewLength--]='%';
}
else{
str[pointToNewLength--]=str[pointToOldLength];
}
--pointToOldLength;
}
return;
}
};