时间限制:1秒 空间限制:32768K
本题知识点: 字符串
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy。则经过替换之后的字符串为We%20Are%20Happy。
代码:
class Solution {
public:
void replaceSpace(char *str,int length) {
if(str == NULL && length < 0)
return;
int newlength = 0;
int replacenum = 0;
int i=0;
while(i < length){
if(str[i]==' ')
replacenum++;
i++;
}
newlength = length + 2 * replacenum;
if(newlength == length)
return;
int oldnum = length;
int newnum = newlength;
while(oldnum >= 0 && newnum > oldnum){
if(str[oldnum] == ' '){
str[newnum--] = '0';
str[newnum--] = '2';
str[newnum--] = '%';
}
else
str[newnum--] = str[oldnum];
oldnum--;
}
}
};