First, we count the number of spaces between string. Because we are going to replace those spaces with “%20”, which means the new length of s will become length + spaceCnt * 2.
void replaceSpaces(char* s, int length){
int spaceCnt = 0, newLenth = 0;
for(int i = 0; i<length; ++i){
if(s[i] == ' ') ++spaceCnt;
}
newLenth = length + spaceCnt *2;
int j = newLenth - 1;
for(int i = length - 1; i>=0; --i){
if ( s[i] == ' '){
s[j--] = '0';
s[j--] = '2';
s[j--] = '%';
}else s[j--] = s[i];
}
}