替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
 

思路

第一步先遍历整个字符串,确定其中有多少个空格。

将字符串的长度增长,增长空格数乘以2。

第三个,重新遍历字符串,遍历的顺序为倒序,从字符串的最后一个字符往前遍历,如果不是空格,增加字符串添加到增长后的字符串的末尾,这里的添加类似于入栈操作,如果是空格,增将空格替换为“%20”。

class Solution {
public:
    void replaceSpace(char *str,int length) {
        if(str == NULL || length <= 0) return;
        int count_space = 0;
        int curr_count_space = 0;
        for(int i = 0; i < length; i++)
            if(str[i]==' ') count_space++;
        str[length + count_space*2] = '';
        for(int i = 0; i < length + count_space*2; i++){
            if(str[length - 1 - i] == ' '){
                str[length + count_space*2- 1 - i - curr_count_space*2] = '0';
                str[length + count_space*2- 2 - i - curr_count_space*2] = '2';
                str[length + count_space*2- 3 - i - curr_count_space*2] = '%';
                curr_count_space++;
            }
            else str[length + count_space*2- 1 - i - curr_count_space*2] = str[length - i - 1];
        }
    }
};
原文地址:https://www.cnblogs.com/zhousong918/p/10266722.html