题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
void replaceSpace(char *str, int length) {
if (str == NULL || length <= 0)
return;
int oldlength = 0;
int newlength = 0;
//查找原字符串和空格个数
int numspace = 0;
for (int i = 0; str[i]!='\0'; i++)
{
oldlength ++;
if (str[i] == ' ')
{
numspace++;
}
}
newlength = oldlength + 2 * numspace;
if (newlength > length)//如果计算后的长度大于总长度就无法插入
return;
//将空格替换为“%20”
for (int i = newlength,j = oldlength; i >= 0 && i >= j;i--, j--)
{
if (str[j] == ' ')
{
str[i] = '0';
str[i-1] = '2';
str[i-2] = '%';
i=i-2;
}
else{
str[i] = str[j];
}
}
}
};