5. 替换空格
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路
思路就是书上的思路。两个指针操作。
传入的指针实际上上是数组头;
注意参数 length 不是字符的长度,而是数据空间的长度;
所以,字符的长度,要根据 ‘\0’ 的条件,自己去计算一遍;
好久没写指针,都忘了 怎么遍历值了。。。。
代码
class Solution {
public:
void replaceSpace(char *str,int length) {
if (str == NULL || length <= 0) return;
int n_blank = 0;
int actual_length = 0;
int i = 0;
while (*(str + i) != '\0') {
actual_length++;
if ( *(str + i) == ' ' ) n_blank++;
i++;
}
int new_len = actual_length + 2*n_blank;
if (new_len > length) return;
int idx_1 = actual_length;
int idx_2 = new_len;
while (idx_1 >= 0 && idx_1 < idx_2) {
if (*(str+idx_1) != ' ') {
*(str + idx_2) = *(str+idx_1);
idx_2--;
}
else {
*(str + idx_2) = '0';
idx_2--;
*(str + idx_2) = '2';
idx_2--;
*(str + idx_2) = '%';
idx_2--;
}
idx_1--;
}
}
};