空格替换练习

来源:互联网 发布:.net水电管理系统源码 编辑:程序博客网 时间:2024/06/03 16:53

请编写一个方法,将字符串中的空格全部替换为“%20”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。
给定一个string iniString 为原始的串,以及串的长度 int len, 返回替换后的string。
测试样例:
“Mr John Smith”,13
返回:”Mr%20John%20Smith”
”Hello World”,12
返回:”Hello%20%20World”

题目非常简单,唯一需要注意的是需要首先在尾后递增,而不是字符串后面一开始就有那么大的空间。

class Replacement {public:    string replaceSpace(string iniString, int length) {        if(length<=0)            return string{};        int countspace=0;        for(int i=0;i!=length;++i)            {            if(iniString[i]==' '){                ++countspace;                iniString+="xx";            }        }        int lensum=length+2*countspace;        int j=lensum-1;        for(int i=length-1;i>=0;--i)            {             if(iniString[i]==' ')                {                  iniString[j]='0';                  iniString[j-1]='2';                  iniString[j-2]='%';                  j=j-3;                }             else                 {                 iniString[j]=iniString[i];                 --j;             }        }        return iniString;    }};
0 0