题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy
class Solution {
public:
void replaceSpace(char *str, int length) {
if (str == NULL || length <= 0) return;
char*p = str;
int numofspaces = 0;
int originallen = 0;
while (*p != '\0') {
if (*p == ' ') ++numofspaces; //我竟然把这条语句放在后面了,我真的是蠢一匹,如果第一个是' '空格咋办》?》?
++p;
++originallen;
//if (*p == ' ') ++numofspaces;
}
int newstrlen = originallen + numofspaces * 2;
if (newstrlen>length)
return;
char* pold = p;
char* pnew = str + newstrlen;
while (pold >= str){
while (pold >= str&&*pold != ' ') {
*pnew-- = *pold--;
}
if (pold<str) break;
*pnew-- = '0';
*pnew-- = '2';
*pnew-- = '%';
pold--;
}
return;
}
};