首页 > 其他 > 详细

将字符串中的空格替换为%20

时间:2015-11-03 00:51:19      阅读:296      评论:0      收藏:0      [点我收藏+]

------------------------------------------------------------------------------------------------------

       例如:有字符串we are family,实现后的字符串为we%20are%20family。

    如果从前向后,遇空格替换空格,那么family必将向后移动两次;那么我们可以从后向前实现,

先预留足够的空间,先移动family,再移动are,遇空格填充即可。

------------------------------------------------------------------------------------------------------

C语言代码:

# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <assert.h>


# define MAX 50

void insert(char *p)
{
     assert(p);
     char *pstart = NULL;
     char *pend = NULL;
     int black = 0;
     int size = strlen(p);
     
     pstart = p + size;
 
     while (*p)                         //统计预留空格数
     {
          if (*p == ‘ ‘)
          {
               black++;
           }
          p++;
     }
    
     pend = pstart + (black * 2);
    
     while (pstart < pend)
     {
          if (*pstart != ‘ ‘)
          {
               *pend = *pstart;
               pstart--;
               pend--;
          }
          else
          {
               *pend-- = ‘0‘;
               *pend-- = ‘2‘;
               *pend-- = ‘%‘;
               *pstart--;
          }
     }
}
int main()
{
     char str[MAX] = "";
     
     printf("请输入字符串:");
     gets(str);
     
     insert(str);
     printf("%s\n",str);
     
     system("pause");
     return 0;
}

------------------------------------------------------------------------------------------------------

干活小知识:循环语句,应当将最长的循环放在最内层,最短的放在最外层,以减少CPU跨切循环层数,建议for循环的循环控制变量采取“半开半闭”的写法。

------------------------------------------------------------------------------------------------------

本文出自 “无名小卒” 博客,请务必保留此出处http://814193594.blog.51cto.com/10729329/1708947

将字符串中的空格替换为%20

原文:http://814193594.blog.51cto.com/10729329/1708947

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!