class Solution {
public:
void replaceSpace(char *str, int length) {
if (str == NULL || length < 0)
return;
int i = 0; int j = 0;
int num = 0;
int oldlength=0;
//先遍历一遍计算出空格的数量num,向后移动2*num
while (str[i] != '\0') {
oldlength++;
if (str[i] == ' ') {
num ++;
}
i++;
}
//从后向前找空格
int newlength = oldlength + num*2;
if (newlength > length) return;
int p_old = oldlength;//注意不用减一,\0也要算在里面
int p_new = newlength;
while (p_old>=0&&p_old<p_new) {
if (str[p_old] == ' ') {
str[p_new--] = '0';
str[p_new--] = '2';
str[p_new--] = '%';
}
else {
str[p_new] = str[p_old];
p_new--;
}
p_old--;//记得无论是否是空格p_old都要向前移动
}
}
};