题目描述

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

class Solution {
public:
	void replaceSpace(char *str,int length) 
    {
        if(str == nullptr || length <0)
            return ;
        int  i = 0;
        int count_black = 0;
        int oldnumber = 0;
       
        while('\0' != str[i])
        {
            oldnumber++;
            if(' ' == str[i])
                count_black++;
            i++;
        }
        int newnumber = oldnumber + count_black*2;
        int poldnumber = oldnumber;
        int pnewnumber = newnumber;
        while(poldnumber>= 0 && poldnumber < pnewnumber)
        {
            if(str[poldnumber] == ' ')
            {
                str[pnewnumber--] = '0';
                str[pnewnumber--] = '2';
                str[pnewnumber--] = '%';
            }
            else
                str[pnewnumber--] = str[poldnumber];
            poldnumber--;
        }
	}
};

<stron>:替换空格</stron>