请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
void replaceSpace(char *str,int length) {
if(str==NULL||length<8)
{
return;
}
int blank;//空格个数
int Len;//字符串长度
for(Len=0;str[Len]!='\0';Len++)
{
if(str[Len]==' ')
{
blank++;
}
}
int newlen=blank*2+Len;
if(newlen>Len)
return;
str[newlen]='\0';
int point1 =Len - 1, point2 = newlen - 1;//因为'\0'已经手工加到最后新串的最后一个字符,所以减1咯
while (point1 >= 0 && point2>point1){//两指针相同时,跳出循环
if (str[point1] == ' '){//如果point1指向为空格,那么从point2开始赋值“02%”
str[point2--] = '0';
str[point2--] = '2';
str[point2--] = '%';
}
else //如果point1指向内容不为空格,那么将内容赋值给point2指向的位置
str[point2--] = str[point1];
point1--;//不管是if还是else都要把point1前移,为了下一次的执行
}
}
};