3_10空格替换练习题

2017-09-08  本文已影响5人  X_Y

请编写一个方法,将字符串中的空格全部替换为“%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) {
        // write code here
        // 统计空格数目
        int num_sps = 0;
        for(int i=0; i<length; ++i){
            if(' ' == iniString[i]){
                ++num_sps;
            }
        }
        int r_idx = length + 2 * num_sps - 1;
        int l_idx = length - 1;
        // 需要主动扩容
        iniString.resize(length + 2*num_sps, '0');
        while(l_idx != 0){
            if(' ' == iniString[l_idx]){
                iniString[r_idx--] = '0';
                iniString[r_idx--] = '2';
                iniString[r_idx--] = '%';
                l_idx--;
            }else{
                iniString[r_idx--] = iniString[l_idx--];
            }
        }
        return iniString;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读