题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解题思路
水题,灵活使用std::vector
即可
AC代码
class Solution {
public:
void replaceSpace(char *str, int length) {
vector<char> vec;
for (int i = 0; str[i] != '\0'; ++i) {
if (str[i] != ' ') {
vec.push_back(str[i]);
} else {
vec.push_back('%');
vec.push_back('2');
vec.push_back('0');
}
}
memset (str, 0, length);
int len = vec.size();
for (int i = 0; i < len; ++i) {
str[i] = vec[i];
}
str[len] = '\0';
}
};