今天的作业是用%20替代字符串中的空格:
第一种是较简单的方法,利用两个数组进行复制和字符向后推移,从前向后替换。
#include<stdio.h>
int main()
{
char str[50]=" h e llo ";
char arr[50]={0};
int i,j=0;
for(i=0;str[i]!='\0';i++)
{
if(str[i]==' ')
{
arr[j]='%';
arr[j+1]='2';
arr[j+2]='0';
j+=3;
}
else
{
arr[j]=str[i];
j+=1;
}
}
printf("%s\n",arr);
return 0;
}
第二种是书写函数进行调用,从后面开始替换,但有漏洞就是当字符前面是空格时就会出现错误的情况,有修改后会继续上传更新。
#include<stdio.h>
void replace(char *p)
{
int old_len=0;
int new_len=0;
int space=0;
while(p[old_len]!='\0')
{
if(p[old_len]==' ')
space++;
old_len++;
}
new_len=old_len + space*2;
while(old_len!=0){
if(p[old_len]==' ')
{
p[new_len--]='0';
p[new_len--]='2';
p[new_len]='%';
}
else
{
p[new_len]=p[old_len];
}
old_len--;
new_len--;
}
}
int main()
{
char str[50]="he llo world ";
replace(str);
printf("%s\n",str);
return 0;
}
1336

被折叠的 条评论
为什么被折叠?



