字符串替换空格: 请实现一个函数,把字符数组中的每个空格替换成“%20”。 例如输入“we are happy.”,则输出“we are happy.”


   
   
/*  版本1:   将空格后面的元素后移,然后在将空格替换为%20。   缺点:    时间复杂度为O(n^2) */ char* ReplaceBlank1(char string[]) {  if (string != NULL)  {   int index = 0;   while (string[index] != '\0')   {    //遇到空格进行替换    if (' ' == string[index])    {     int i = strlen(string);     //将空格后面的元素进行后移     for (i; i > index; i--)     {      string[i + 2] = string[i];     }     string[index] = '%';     string[++index] = '2';     string[++index] = '0';    }    index++;   }  }  return string; }
/*  版本2:   用两个指针从字符串末尾从前进行遍历。   需要先得到字符串长度和替换之后字符串的长度。   时间复杂度:O(n)
  we are happy. */
char* ReplaceBlank2(char arr[], int length)//length为字符串的strlen()结果 {  if (NULL == arr || length <= 0)   return NULL;  int startStrLength = 0;//开始时字符串的长度(strlen()结果)  int endStrLength = 0;//替换结束时字符串的长度(strlen()结果)  int i = 0;  int count = 0;  while ('\0' != arr[i])  {   if (' ' == arr[i])    count++;   i++;  }  //在进行替换之后字符串会变长,为了防止字符被覆盖,所以从后向前进行  startStrLength = length;//指向最后一个字符'\0'  endStrLength = startStrLength + count * 2;//指向替换结束最后一个字符  while (startStrLength >= 0 && endStrLength >= 0)  {   if (' ' != arr[startStrLength])   {    //字符转移    arr[endStrLength] = arr[startStrLength];   }   else   {    //空格替换    arr[endStrLength] = '0';    arr[--endStrLength] = '2';    arr[--endStrLength] = '%';   }   //向前移动   startStrLength--,endStrLength--;  }  return arr; }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值