题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
void replaceSpace(char *str,int length) {
int num=0;
int realLenth = 0;
for(int i = 0;i<length;i++)
{
if(str[i] == ' ')
num++;
if(str[i]!='\0')
realLenth++;
else
break;
} // 计算space个数,确定字符串延长的长度
int posEnd = realLenth + 2*num -1, pos = realLenth-1;
while(pos>=0)
{
if(str[pos] == ' ')
{
str[posEnd] = '0';
str[posEnd-1] = '2';
str[posEnd-2] = '%';
posEnd -= 3;
}
else
{
str[posEnd] = str[pos];
posEnd--;
}
pos--;
}
str[realLenth + 2*num]='\0'; //字符串末尾标记
}
};