替换空格

题目描述

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

C++11(clang++ 3.9)

class Solution {
public:
    void replaceSpace(char *str,int length) {
        // input check
        if(length <= 0)
        {
            return;
        }
        
        int space_count = 0;
        for(int i = 0; i < length; i++)
        {
            if(str[i] == ' ')
            {
                space_count++;
            }
        }
        
        int new_index = length + space_count * 2 - 1;
        for(int i = length - 1; i >= 0; i--)
        {
            if(str[i] != ' ')
            {
                str[new_index--] = str[i];
            }
            else
            {
                str[new_index--] = '0';
                str[new_index--] = '2';
                str[new_index--] = '%';
            }
        }
    }
};

 

posted @ 2020-03-07 18:35  hotwater99  阅读(94)  评论(0编辑  收藏  举报