替换空格
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路
从右往左复制。
class Solution {
public:
void replaceSpace(char *str,int length) {
if(str == nullptr || length <= 0 ) return;
int cnt = 0;
for(int i = 0 ; i < length ; i++)
if(str[i] == ' ')
cnt++;
if(!cnt) return;
int new_length = length + cnt*2;
for(int i = length ; i >= 0 ; i--){//结束符也复制
if(str[i] == ' '){
str[new_length--] = '0';
str[new_length--] = '2';
str[new_length--] = '%';
}
else{
str[new_length--] = str[i];
}
}
}
};