void replaceSpace(char *str,int length) { if(str==NULL||length<=0) return; int originlen=0; int newlen=0; int space=0; while(str[originlen]!=‘\0‘) { if(str[originlen]==‘ ‘) space++; originlen++; } originlen++; newlen=originlen+2*space; if(originlen==1||space==0||newlen>length) return; char *p1,*p2; p1=&str[originlen-1]; p2=&str[newlen-1]; for(int i=0;i<newlen;i++) { if(*p1!=‘ ‘) { *p2=*p1; p1--; p2--; } else { *p2=‘0‘; p2--; *p2=‘2‘; p2--; *p2=‘%‘; p2--; p1--; } } return; }
把代码整理简化一下:
void replaceSpace(char *str,int length) { if(str==NULL||length<=0) return; int originlen=0; int newlen=0; int space=0; while(str[originlen]!=‘\0‘) { if(str[originlen++]==‘ ‘) space++; } originlen++; newlen=originlen+2*space; if(originlen==1||space==0||newlen>length) return; int p1=originlen-1; int p2=newlen-1; for(int i=0;i<newlen;i++) { if(str[p1]!=‘ ‘) str[p2--]=str[p1--]; else { str[p2--]=‘0‘; str[p2--]=‘2‘; str[p2--]=‘%‘; p1--; } } return; }
时间: 2024-11-08 13:33:12