题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
void replaceSpace(char *str, int length) {
if (str == NULL)
return;
int space_num = 0;
for (int i = 0; i<length; ++i)
{
if (str[i] == 32)
space_num++;
}
int i = length-1;
for (int j = space_num * 2 + length-1; i>=0; )
{
if (str[i] == 32)
{
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
--i;
}
else
str[j--] = str[i--];
}
//strcpy(str, temp);
}
};