题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
注意事项:
《剑指offer》上的length为str的最大长度空间
而牛客上的lenght为str的长度,包括了'\0'
由于str为数组指针,故只能在原数组上修改,选用后替换法
class Solution {
public:
void replaceSpace(char *str, int length) {
if (str == nullptr || length <= )
return;
int strLen = , spaceNum = , newLenght = ;
for (strLen = ; str[strLen] != '\0'; ++strLen)
if (str[strLen] == ' ')
spaceNum++;
newLenght = strLen + spaceNum * ;
for (int i = newLenght, j = strLen; i >= ; --j)
if (str[j] == ' ')
{
str[i--] = '';
str[i--] = '';
str[i--] = '%';
}
else
str[i--] = str[j];
}
};