剑指offer刷题第二题

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

 

class Solution {
public:
	void replaceSpace(char *str,int length) {
        int oldlength=0, newlength=0,count=0;
        for(int i=0;str[i]!='\0';i++)
        {
            oldlength++;
            if(str[i]==' ') count++;
            
        }
        newlength=oldlength+2*count;
        while(oldlength>=0)
        {
            if(str[oldlength]==' ')
            {
                str[newlength--]='0';
                str[newlength--]='2';
                str[newlength--]='%';
               
            }
            else
            {
                str[newlength--]=str[oldlength];
                
            }
            oldlength--;
            
        }
	}
};

 

你可能感兴趣的:(剑指offer)