您的位置:首页 > Web前端

(剑指offer)替换空格

2016-09-03 19:57 246 查看
题目:请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“we are happy.”,则输出“we%20are%20happy.”。

假设我们在原来的字符串上做替换,并且保证输入的字符串上做替换,并且保证输入的字符串后面有足够的的空余内存。

我的代码:

void replace_space(char *pstr, int length)
{
if(NULL == pstr){
return;
}
int size = strlen(pstr);
int countspace = 0;
for(int i=0; i<size; i++){
if((' '==pstr[i])){
countspace++;
}
}
int step = 2*countspace;
if(size+step > length){
return;
}
for(int i=size; i>=0&&step>=0; i--){
if(pstr[i] != ' '){
pstr[i+step]=pstr[i];
}else{
pstr[i+step] = '0';
pstr[i+step-1] = '2';
pstr[i+step-2] = '%';
step -= 2;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: