题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
时间限制:1秒 空间限制:32768K
主要思想:根据空格的数量得到新字符串长度,将尾部字符依次向后移,遇到空格将“%20”插入,直到空格被替换完。
class Solution {
public:
void replaceSpace(char *str,int length) {
if (str == NULL || length <= 0)
return;
int spacenum = 0; //定义空格的数量
int i = 0; //定义字符串数组下标
while (str[i] != '\0') //统计空格的数量
{
if (str[i] == ' ')
++spacenum;
++i;
}
int newlen = length + spacenum * 2; //定义新字符串的长度
int oldindex = length; //定义旧字符串末尾下标
int newindex = newlen; //定义新字符串末尾下标
while (oldindex >= 0 && oldindex < newindex)
{
if (str[oldindex] != ' ') //若当前字符不为空格则向后移动
str[newindex--] = str[oldindex];
else
{
str[newindex--] = '0';
str[newindex--] = '2';
str[newindex--] = '%';
}
--oldindex;
}
}
};