请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
void replaceSpace(char *str,int length) {
if (str == NULL || length <= 0) {
return;
}
//count
int spaceCnt = 0, size = 0;
for (int i = 0; str[i] != ' '; i++) {
if (str[i] == ' ') {
spaceCnt++;
}
size++;
}
int newSize = size+2*spaceCnt;
if (newSize > length) {
return;
}
//from back to front
for (int i = size, j = newSize; i >= 0; i--) {
if (str[i] != ' ') {
str[j--] = str[i];
} else {
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
}
}
}
};