题目:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
程序:
#include<stdio.h>
//将字符串中的空格替换成%20
void replaceBlank(char *str,int length){
int i=0,count=0,j=0;
while(str[i]!='\0'){
if(str[i]==' ')
count++;
i++;
}
j=i+count*2;
str[j--]='\0';
i--;
while(i>=0&&j>0){
if(str[i]!=' ')
{
str[j--]=str[i];
}
else
{
str[j--]='0';
str[j--]='2';
str[j--]='%';
}
i--;
}
}
int main(){
char s[]="we are student.";
printf("%s\n",s);
replaceBlank(s,16);
printf("%s",s);
return 1;
}
运行结果: