字符替换
使用辅助数组 是解题重点
初始版本:
char* replaceSpaces(char* S, int length){
int i,j;
char* new_s = (char*)malloc(sizeof(char)*(length*3)+1);
i = j = 0;
for(;i<length;i++){
if(S[i]!=' ')
new_s[j++] = S[i];
else{
new_s[j++] = '%';
new_s[j++] = '2';
new_s[j++] = '0';
}
}
new_s[j] = '\0';
return new_s;
}
改进: 减少数组数量
char* replaceSpaces(char* S, int length){
int i,j,len;
i = len = 0;
while(i<length){
if(S[i] == ' ')
len++;
i++;
}
char* new_s = (char*)malloc(sizeof(char)*(length+2*len+1));
i = j = 0;
for(;i<length;i++){
if(S[i]!=' ')
new_s[j++] = S[i];
else{
new_s[j++] = '%';
new_s[j++] = '2';
new_s[j++] = '0';
}
}
new_s[j] = '\0';
return new_s;
}
再改进:辅助数组再减少
不申请变换后字符的数量,在原字符串修改
char* replaceSpaces(char* S, int length){
int i,j;
char* new_s = (char*)malloc(sizeof(char)*(length+1));
i = 0;
for(;i<length;i++){
new_s[i] = S[i];
}
new_s[i] = '\0';
i = j = 0;
for(;i<length;i++){
if(new_s[i]!=' ')
S[j++] = new_s[i];
else{
S[j++] = '%';
S[j++] = '2';
S[j++] = '0';
}
}
S[j] = '\0';
return S;
}