2021-05-06

今天的作业是用%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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值