zoukankan      html  css  js  c++  java
  • 剑指Offer-- 替换空格

    题目描述

    请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
     
    class Solution {
    public:
        void replaceSpace(char *str,int length) {
            int i = 0,count = 0,ncount = 0,bcount =0;         // length 为字符数组的总容量
            if (str == nullptr || length <= 0)
                return;                     // 如果为空字符串或者长度小于等于0,则返回
            while ( *(str + i) != '')  // 尤其注意这个反斜杠的方向
            {
                if ( *(str + i) == ' ')
                {
                    bcount++;            // 首先遍历整个数组找出含有的空格数存入bcount中
                }
                i++;                     // 控制循环变量
                count++;                 // 计算出实际的字符的长度
            }
            ncount = count + bcount * 2;      //  替换后新的字符数组的长度 
            if ( ncount > length)
                return;                      // 如果新的长度大于总容量,则说明装不下,返回
            int indexofnew = ncount;
            int indexofori = count;
            while (indexofori >= 0 && indexofnew > indexofori)  
            {
                if ( *( str + indexofori) == ' ')
                {                              //若碰到空格应进行的处理
                    *(str + indexofnew) = '0';
                    indexofnew--;
                    *(str + indexofnew) = '2';
                    indexofnew--;
                    *(str + indexofnew) = '%';
                    indexofnew--;
                }
                else                 // 若不碰到空格则把前一个指针指向的内容赋给后一个指针指向的内存
                {
                    *(str + indexofnew) = *(str + indexofori);
                    indexofnew--;
                }
                indexofori--;
            }
            
        }
    };

    思路二:

    java中的函数

    public class Solution {
        public String replaceSpace(StringBuffer str) {
            return str.toString().replaceAll("\s", "%20");
        }
    }
  • 相关阅读:
    猜数游戏
    计算数组长度
    python 将IP地址转换成打包后的32位格式
    nutch-2.2.1 hadoop-1.2.1 hbase-0.92.1 集群部署
    Julien Nioche谈Apache Nutch 2的特性及产品路线图
    一次心惊肉跳的服务器误删文件的恢复过程
    Http长连接200万尝试及调优
    zookeeper 系列
    Enhancing the Scalability of Memcached
    linux杂谈(十八):DNS服务器的配置(一)
  • 原文地址:https://www.cnblogs.com/simplepaul/p/6725235.html
Copyright © 2011-2022 走看看