剑指offer 替换字符串中的空格

void replaceSpace(char *str,int length) {
if(str==NULL||length<=)
return;
int originlen=;
int newlen=;
int space=;
while(str[originlen]!='\0')
{
if(str[originlen]==' ')
space++;
originlen++;
}
originlen++;
newlen=originlen+*space;
if(originlen==||space==||newlen>length)
return;
char *p1,*p2;
p1=&str[originlen-];
p2=&str[newlen-];
for(int i=;i<newlen;i++)
{
if(*p1!=' ')
{
*p2=*p1;
p1--;
p2--;
}
else
{
*p2='';
p2--;
*p2='';
p2--;
*p2='%';
p2--;
p1--;
} }
return;
}

把代码整理简化一下:

void replaceSpace(char *str,int length) {
if(str==NULL||length<=)
return;
int originlen=;
int newlen=;
int space=;
while(str[originlen]!='\0')
{
if(str[originlen++]==' ')
space++;
}
originlen++;
newlen=originlen+*space;
if(originlen==||space==||newlen>length)
return;
int p1=originlen-;
int p2=newlen-;
for(int i=;i<newlen;i++)
{
if(str[p1]!=' ')
str[p2--]=str[p1--];
else
{
str[p2--]='';
str[p2--]='';
str[p2--]='%';
p1--;
} }
return;
}
上一篇:Python类总结-继承-子类和父类,新式类和经典类


下一篇:Codeforces Round #164 (Div. 2)